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.

Recommended Answers

All 3 Replies

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

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);
}
execlp(APP_PATH, APP_PATH, "some value");

Don't forget to null-terminate the arglist:

execlp(APP_PATH, APP_PATH, "some value", 0);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.