954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

system() and getppid()

I want to launch a new process from a given string of input (including parameter).
I tried to use system() but it appears that in the child process, getppid() is not the same as the caller in some runs (probably because system uses the shell as command interpreter).

However, if I fork and then use exec(), it is complicated to parse the parameter.

Anyone knows a way to get around this problem? Or is there any library that helps parse a string of input into program parameters like shells often do?

Thank you very much in advance.

paddy8788
Newbie Poster
8 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 

Yes use fork then execlp(or one of the family of functions from exec).

gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
 

I think this is what you want:

main.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define APP_PATH "/path_to_testit/testit"

int main(int argc, char**argv)
{
	if (fork())
	{
		fprintf(stdout, "parent pid->%d\n", getpid());
	}
	else
	{
		execlp(APP_PATH, APP_PATH, "some value");
	}
	exit(EXIT_SUCCESS);
}


testit.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char**argv)
{
	fprintf(stdout, "we passed->%s\n", argv[1]);
	fprintf(stdout, "client's parent->%d\n", getppid());
	exit(EXIT_SUCCESS);
}
gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
 
execlp(APP_PATH, APP_PATH, "some value");


Don't forget to null-terminate the arglist:

execlp(APP_PATH, APP_PATH, "some value", 0);
nezachem
Posting Shark
903 posts since Dec 2009
Reputation Points: 719
Solved Threads: 194
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: