objective c - executing shell command with | (pipe) using NSTask -
i'm trying execute comamnd ps -ef | grep test
using nstask can't | grep test included in nstask:
this i'm using output of ps -ef string need somehow pid of process test
nstask *task; task = [[nstask alloc] init]; [task setlaunchpath: @"/bin/ps"]; nsarray *arguments; arguments = [nsarray arraywithobjects: @"-ef", nil]; [task setarguments: arguments]; nspipe *pipe; pipe = [nspipe pipe]; [task setstandardoutput: pipe]; nsfilehandle *file; file = [pipe filehandleforreading]; [task launch]; nsdata *data; data = [file readdatatoendoffile]; nsstring *string; string = [[nsstring alloc] initwithdata: data encoding: nsutf8stringencoding]; nslog (@"got\n%@", string);
piping feature provided shells, such /bin/sh
. may try launching command via such shell:
/* ... */ [task setlaunchpath: @"/bin/sh"]; /* ... */ arguments = [nsarray arraywithobjects: @"-c", @"ps -ef | grep test", nil];
however, if let user supply value (instead of hard-coding e.g. test
), making program susceptible shell injection attacks, kind of sql injection. alternative, doesn't suffer problem, use pipe object connect standard output of ps
standard input of grep
:
nstask *pstask = [[nstask alloc] init]; nstask *greptask = [[nstask alloc] init]; [pstask setlaunchpath: @"/bin/ps"]; [greptask setlaunchpath: @"/bin/grep"]; [pstask setarguments: [nsarray arraywithobjects: @"-ef", nil]]; [greptask setarguments: [nsarray arraywithobjects: @"test", nil]]; /* ps ==> grep */ nspipe *pipebetween = [nspipe pipe]; [pstask setstandardoutput: pipebetween]; [greptask setstandardinput: pipebetween]; /* grep ==> me */ nspipe *pipetome = [nspipe pipe]; [greptask setstandardoutput: pipetome]; nsfilehandle *grepoutput = [pipetome filehandleforreading]; [pstask launch]; [greptask launch]; nsdata *data = [grepoutput readdatatoendoffile]; /* etc. */
this uses built-in foundation functionality perform same steps shell when encounters |
character.
finally others have pointed out, usage of grep
overkill. add code:
nsarray *lines = [string componentsseparatedbystring:@"\n"]; nsarray *filteredlines = [lines filteredarrayusingpredicate: [nspredicate predicatewithformat: @"self contains[c] 'test'"]];
Comments
Post a Comment