怎么使用fork函数创建子进程的子进程
1个回答
展开全部
//main1.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv)
{
printf("program 1 started\n");
char *newargv[] = { "hello", "world" };
char *newenviron[] = { NULL };
int pid=fork();
if(pid < 0)
exit(EXIT_FAILURE);
if(pid == 0)
{
execve("./main2", newargv, newenviron); //打开同级目录下的main2程序
perror("execve"); /* execve() only returns on error */
exit(EXIT_FAILURE);
}
//父进程继续
sleep(5); //do something
printf("Promgram 1 finished!\n");
return 0;
}
//main2.c
#include <stdio.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
printf("program 2 started\n");
int i;
for(i = 0; i<argc;i++)
printf("%s\n",argv[i]);
sleep(5); //do something
printf("Promgram 2 finished!\n");
return 0;
}
然后编译
gcc -o main1 main1.c
gcc -o main2 main2.c
运行
./main1
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv)
{
printf("program 1 started\n");
char *newargv[] = { "hello", "world" };
char *newenviron[] = { NULL };
int pid=fork();
if(pid < 0)
exit(EXIT_FAILURE);
if(pid == 0)
{
execve("./main2", newargv, newenviron); //打开同级目录下的main2程序
perror("execve"); /* execve() only returns on error */
exit(EXIT_FAILURE);
}
//父进程继续
sleep(5); //do something
printf("Promgram 1 finished!\n");
return 0;
}
//main2.c
#include <stdio.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
printf("program 2 started\n");
int i;
for(i = 0; i<argc;i++)
printf("%s\n",argv[i]);
sleep(5); //do something
printf("Promgram 2 finished!\n");
return 0;
}
然后编译
gcc -o main1 main1.c
gcc -o main2 main2.c
运行
./main1
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询