标准UNIX方式是通过电话exec(3)使用fork(2)其次(还有的全家他们,选择任何一个适合您需要的最好的)。
例子来说明使用:
#include
#include
#include
int main(int argc, char **argv)
{
pid_t pid;
printf("before fork\n");
if ((pid = fork()) < 0) {
//It may fail -- super rare
perror("Fork failed");
} else if (pid > 0) {
//If it returns a positive number, you're in the parent process and pid holds the pid of the child
printf("Mah kid's pid is %d\n", pid);
printf("Mine's %d\n", getpid());
} else {
//If it returns zero, you're in the child process
//you can do some preparatory work here (e.g., close filedescriptors)
printf("I'm the child and my pid is %d\n", getpid());
//exec will replace the process image with that of echo (wherever in the PATH environment variable it is be found (using the execlP version here)
execlp("echo", "echo", "hello world from echo; I'm now the child because I've replaced the original child because it called an exec function", (char*)NULL);
printf("This won't run because now we're running the process image of the echo binary. Not this.");
}
return EXIT_SUCCESS;
}