LinuxQuestions.org
Social Bookmarking all things Linux and Open Source
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices

Reply
 
Thread Tools Search this Thread
Old 02-11-2008, 11:11 AM   #1
revof11
Member
 
Registered: Nov 2003
Location: Macungie, PA
Distribution: Fedora Core 9, Gentoo 2008.0
Posts: 108
Thanked: 0
C/C++ - popen - launch process in specific directory


[Log in to get rid of this advertisement]
All,

I can successfully launch popen and grab the stdout using the following code snippit:

Code:
string getStdoutFromCommand(string cmd)
{
  // setup
  string data;
  FILE *stream;
  char buffer[MAX_BUFFER];

  // do it
  stream = popen(cmd.c_str(), "r");
  while ( fgets(buffer, MAX_BUFFER, stream) != NULL )
    data.append(buffer);
  pclose(stream);

  // exit
  return trim(data);
}
What I want to do is launch cmd in a specific directory. Basically, I want to change to the directory and launch the command. The "raw shell" equivalent (*nix or Windows) being:

Code:
cd "SomeDir"
cmd
Is there any way to do this with the popen or exe/execl commands? I couldn't find anything in the man pages or online about it.
revof11 is offline     Reply With Quote
Old 02-11-2008, 11:57 AM   #2
jim mcnamara
Member
 
Registered: May 2002
Posts: 964
Thanked: 0
popen executes the shell in a subprocess -- concatenate two commands into one

Suppose your command looks like this now:
Code:
ls -l somefile
Make the command string look like this:
Code:
cd /path/to/somewhere && ls -l somefile
jim mcnamara is offline     Reply With Quote
Old 02-11-2008, 12:17 PM   #3
Matir
Moderator
 
Registered: Nov 2004
Location: Atlanta, GA
Distribution: Ubuntu
Posts: 8,356
Thanked: 17
Or you could have the parent process cwd, then launch via popen/exec*.
Matir is offline     Reply With Quote
Old 02-11-2008, 02:04 PM   #4
revof11
Member
 
Registered: Nov 2003
Location: Macungie, PA
Distribution: Fedora Core 9, Gentoo 2008.0
Posts: 108
Thanked: 0

Original Poster
Talking

Quote:
Originally Posted by Matir View Post
Or you could have the parent process cwd, then launch via popen/exec*.
I wasn't sure if changing directories on the parent process would do it or not. After a quick test, you are right... it does. I will use this solution for run.

Thanks for the quick replies!
revof11 is offline     Reply With Quote
Old 02-26-2009, 08:50 PM   #5
bramac2
LQ Newbie
 
Registered: Feb 2009
Posts: 3
Thanked: 0
Quote:
Originally Posted by jim mcnamara View Post
popen executes the shell in a subprocess -- concatenate two commands into one

Suppose your command looks like this now:
Code:
ls -l somefile
Make the command string look like this:
Code:
cd /path/to/somewhere && ls -l somefile

hello..
i tried using && and it works ex:cd /tmp && ls -l.. thank you..
but i was trying this.. chroot /var/chroot && ls -l.. here the ls -l works only after i give an 'exit'
any suggestions, plz..
thanks..
bramac2 is offline     Reply With Quote
Old 02-27-2009, 01:45 AM   #6
ta0kira
Senior Member
 
Registered: Sep 2004
Distribution: FreeBSD amd64 8.0-RELEASE, Slackware64 13.0, Slackware 12.1, Ubuntu Server 8.04, Kubuntu 9.04
Posts: 2,222
Thanked: 45
Quote:
Originally Posted by bramac2 View Post
hello..
i tried using && and it works ex:cd /tmp && ls -l.. thank you..
but i was trying this.. chroot /var/chroot && ls -l.. here the ls -l works only after i give an 'exit'
any suggestions, plz..
thanks..
That's because chroot will give you a sub-shell by default when you don't specify a command to execute. In this case, it's like typing bash && ls.
Kevin Barry
ta0kira is offline     Reply With Quote
Old 03-03-2009, 11:26 PM   #7
bramac2
LQ Newbie
 
Registered: Feb 2009
Posts: 3
Thanked: 0
thank you very much, kevin.
bramac2 is offline     Reply With Quote
Old 03-12-2009, 12:30 AM   #8
bramac2
LQ Newbie
 
Registered: Feb 2009
Posts: 3
Thanked: 0
i have another question.. i used popen in my c file to chroot and do some actions..
the executable generated from my c file when run from terminal works fine..
but when i call the executable from a php file (which is a part of my Wordpress blog plugin run on Apache server) the chroot does not work and the popen returns 32512 which i think is a failure to fork a subshell for chroot..
any suggestions plz..
thanks, bala
bramac2 is offline     Reply With Quote
Old 03-17-2009, 01:30 AM   #9
ddreggors
LQ Newbie
 
Registered: Oct 2007
Distribution: RedHat, CentOS, Mandriva, and Ubuntu
Posts: 12
Thanked: 0
revof11 I found your code quite handy...

Code:
string getStdoutFromCommand(string cmd) {
	string data;
	FILE *stream;
	int MAX_BUFFER = 256;
	char buffer[MAX_BUFFER];
	cmd.append(" 2>&1");
	stream = popen(cmd.c_str(), "r");
	if (!stream){
		exit(1);
	}
	while (!feof(stream)){
		if (fgets(buffer, MAX_BUFFER, stream) != NULL){
			data.append(buffer);
		}
	}
	pclose(stream);
	return data;
}
One question I have though is if a command is issued that does not return or takes too long is there a way to kill the command and break from the function.

What I am doing with the code above:

I have written a client server application that allows me to exec a command on many servers at once and get the output from that command at the client machine as follows:

Code:
[root@mobile-david ~]# for HOST in `echo "localhost thor"`
> do
> rcomm $HOST hostname -s
> done
localhost: mobile-david
thor: thor

which works amazingly well until I have a jr admin that does something like grepping our entire NFS tree for a string.


I need a way to kill that process from C++ code on say a timer event.

The timer portion is no problem, but killing that process has done little more than leaving it <defunct> until I restart the server, and if it gets called again and again... many <defunct> processes.

Last edited by ddreggors; 03-17-2009 at 01:32 AM..
ddreggors is offline     Reply With Quote
Old 03-26-2009, 08:42 PM   #10
rriggs
Member
 
Registered: Mar 2009
Location: Colorado, US
Distribution: Fedora 10
Posts: 40
Thanked: 3
Quote:
Originally Posted by ddreggors View Post
I need a way to kill that process from C++ code on say a timer event.

The timer portion is no problem, but killing that process has done little more than leaving it <defunct> until I restart the server, and if it gets called again and again... many <defunct> processes.
You need to wait() for your defunct child processes. Call waitpid() with the PID of the process you just killed.
rriggs is offline     Reply With Quote
Old 03-27-2009, 03:57 PM   #11
ddreggors
LQ Newbie
 
Registered: Oct 2007
Distribution: RedHat, CentOS, Mandriva, and Ubuntu
Posts: 12
Thanked: 0
I'm sorry, I did not mention that I have been using waitpid(); The problem was resolved once I removed that popen() from a function outside main() and placed it directly in the main function.

Seems that for some reason if I have it external to main and call the function it is in from main I cannot escape from it properly. Is probably just my poor code though.


I'm not an advanced developer, merely a tinkering tester
ddreggors is offline     Reply With Quote
Old 03-29-2009, 06:11 PM   #12
rriggs
Member
 
Registered: Mar 2009
Location: Colorado, US
Distribution: Fedora 10
Posts: 40
Thanked: 3
Oh -- with popen(), you don't need to kill or wait for the subprocess. pclose() does that for you. Just pclose() the stream and you should be OK. Closing the stream sends a SIGPIPE to the subprocess which should cause it to exit. The process will not get the SIGPIPE until it actually tries to write to the pipe which, for long running processes, may be a while. If you really do need to kill the subprocess, make sure you still call pclose().

You probably want to change the reader while() loop in your code to something like this:

Code:
    while (fgets(buffer, MAX_BUFFER, stream) != NULL) {
        data.append(buffer);
    }
    if (ferror(stream)) {
        // Handle error.
    }
    pclose(stream);
I'm not sure that feof() is true when fgets() returns due to an error, such as the subprocess being killed.

You should consider using exceptions in your code. Don't exit() from C++ applications. It will prevent some destructors from being called. Well-formed C++ applications always return from main().
rriggs is offline     Reply With Quote

Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
kill specific process fj8283888 Linux - General 6 05-31-2007 07:28 AM
Finding pid of a process opened by "popen" Guttorm Programming 2 03-12-2007 03:35 PM
Searching a specific directory for a specific extension? RoaCh Of DisCor Linux - Newbie 3 08-13-2005 04:28 PM
dual monitor, launch program specific display enzo250gto Linux - Software 2 01-27-2005 03:30 PM
How does one launch programs 'out of process' in a terminal window? DKnight Linux - General 5 06-07-2003 11:11 PM


All times are GMT -5. The time now is 05:14 PM.

Main Menu
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Advertisement
Oracle Magazine contains technology strategy articles, sample code, tips, Oracle and partner news, how to articles for developers and DBAs, and more. Click Here to receive a complimentary subscription courtesy of LQ.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
RSS2  LQ Podcast
RSS2  LQ Radio
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: @linuxquestions
Open Source Consulting | Domain Registration