executing shell command with | (pipe) using NSTask

I'm trying to execute this comamnd ps -ef | grep test using NSTask but I can't get the | grep test to be included in the NSTask:

This is what I'm using currently to get the output of ps -ef into a string then I need to somehow get the pid of the 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);

-------------Problems Reply------------

Piping is a feature provided by shells, such as /bin/sh. You may try launching your command via such a shell:

/* ... */
[task setLaunchPath: @"/bin/sh"];
/* ... */
arguments = [NSArray arrayWithObjects: @"-c", @"ps -ef | grep test", nil];

However, if you let the user supply a value (instead of hard-coding e.g. test), you are making the program susceptible to shell injection attacks, which are kind of like SQL injection. An alternative, which doesn't suffer from this problem, is to use a pipe to connect the standard output of ps with the 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. */

Finally as others have pointed out, the usage of grep is overkill. Just add this to your code:

NSArray *lines = [string componentsSeparatedByString:@"\n"];
NSArray *filteredLines = [lines filteredArrayUsingPredicate: [NSPredicate predicateWithFormat: @"SELF contains[c] 'test'"]];

You may need to call [task waitUntilExit] before you launch the task, so that the process can finish running before you read the output.

Category:objective c Views:2 Time:2011-07-22

Related post

  • Python - how to execute shell commands with pipe? 2012-02-22

    I have a case to want to execute the following shell command in Python and get the output, echo This_is_a_testing | grep -c test I could use this python code to execute the above shell command in python, >>> import subprocess >>> su

  • Execute shell command from within MySQL client? 2009-05-30

    In oracle database, command "host" can be used to run bash command from database command window. Is there a equivalent command as "host" in mySql? --------------Solutions------------- You can use the system command. system command, \! command Execute

  • Executing shell commands using PHP, e.g. shell_exec() etc., on a remote host? 2010-09-19

    Is it possible to execute shell commands on a remote computer (not localhost)? For instance things like $output = shell_exec("unzip filename.zip"); You can assume that you have the login credentials of a user account on the remote machine, as well as

  • CTS_ERROR >>> Failed to execute shell command am instrument 2010-11-29

    Using the Android 2.2, API-8, SDK-r7 along with CTS-2.2_r4 suite. Updated the SDK_ROOT environment variable with SDK_r7 tools in “android-cts/tools/startcts” script and the “SDK_ROOT/tools” also included in PATH environment variable. Ran the “android

  • Executing shell command from ruby console returning Permission Denied Error? 2011-03-28

    Getting permission denied error while executing shell command from ruby console. And the same shell command is working from shell. From Shell.. [email protected]:~$ "`grep '^datadir=' /etc/mysql/my.cnf | cut -f 2 -d '='`/db_backups" bash: /db_b

  • How to execute shell command in C? 2011-05-12

    I am having problems executing the shell commands in C. I want to execute a shell command in C then capture the output of shell command and process the output further. I used following code to perform the functionality. But, the issue is when the she

  • How to execute shell commands in android? 2011-07-31

    I am trying to execute shell command through my code for adding entry in Iptables. The following is my piece of code private void createShellCommand(String uidValue_param, String interface_param) { // TODO Auto-generated method stub StringBuilder cmd

  • Execute shell command in c++ 2011-08-29

    I have a question regarding executing shell commands in c++. I'm building an application in winforms, vs 2008. My application has a button, when clicked should decode a binary file to a .csv file. I can decode files by first going to the right direct

  • python: os.system does not execute shell command 2012-03-02

    I need to execute shell command in python program (I have ubuntu). More specifically I want to create graph using graphviz in python script. My code is os.system("dot -Tpng graph.dot -o graph.png") It does not work, but if I just type "dot -Tpng grap

  • php executing shell command gives random output in only in heavy use mode 2012-03-28

    Please help me with this issue that I am facing on production server. I launched an application that saves images in a directory only after checking that it does not already exist. To check if it already exists I used the following command find $file

  • vim: execute shell command without filtering 2009-08-06

    I want to select a block of text (eg. V%) and use the text as input to a shell command (eg. wc or pbcopy) - but I DON'T want to alter the current buffer - I just want to see the output of the command (if any) the continue editting without any changes

  • Executing shell command and reading its output on a C program 2011-03-12

    I am trying to create a function which takes a shell command as an argument , uses fork to spawn a new process which executes the command. I also want to redirect the standard output of the command so the caller of the function can read it using a FI

  • How to store the result of an executed shell command in a variable in python? 2011-12-28

    I need to store the result of a shell command that I executed in a variable. But i couldn get that. I tried like: call=os.system("cat syscall_list.txt | grep f89e7000 | awk '{print $2}'") print call But it prints the result in terminal and prints the

  • Groovy executing shell commands 2008-10-01

    Groovy adds the execute method to String to make executing shells fairly easy; println "ls".execute().text but if an error happens, then there is no resulting output. Is there an easy way to get both the standard error and standard out? (other than c

  • Executing shell command from MySQL 2008-11-14

    I know what I'm looking for is probably a security hole, but since I managed to do it in Oracle and SQL Server, I'll give it a shot: I'm looking for a way to execute a shell command from a SQL script on MySQL. It is possible to create and use a new s

  • PHP exec() will not execute shell command when executed via browser 2009-02-11

    I have a certain PHP script that calls exec() to execute a command to convert a PDF to JPG. This command works fine in bash. To preempt your initial troubleshooting guesses, note the following: safe_mode = Off Permission on the directory containing t

  • How to execute shell command in Javascript 2009-12-10

    I want to write a javascript function which will execute the system shell commands (ls for example) and return the value. How do I achieve this? --------------Solutions------------- What if the client you are executing this javascript is running Wind

  • Executing shell commands from Java 2010-06-17

    I'm trying to execute a shell command from a java application, on the GNU/Linux platform. The problem is that the script, that calls another java application, never ends, although it runs successfully from bash. I tried to debug it: (gdb) bt #0 0xb77

  • I want to execute shell commands from maven's pom.xml 2010-08-16

    I want to execute linux shell commands with maven. Here is what I tried: <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.1.1</version> <executions>

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.090 (s). 11 q(s)