c语言中创建子进程运行外部程序
我想通过自己的程序启动一个外部程序(比如aaa.o),然后在某些条件下关闭这个程序。光用system()不够吧,应该要创建子进程吧?请教关键几步应该怎么写啊?...
我想通过自己的程序启动一个外部程序(比如aaa.o),然后在某些条件下关闭这个程序。光用system()不够吧,应该要创建子进程吧?请教关键几步应该怎么写啊?
展开
2个回答
展开全部
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
int pid1, pid2, pid3, pid4, pid5, pid6;
pid1 = getpid();
printf("PID = %d\n", pid1);
pid2 = fork();
if (pid2 == 0)
{
printf("PID = %d, Parent PID = %d\n", getpid(), getppid());
sleep(30);
exit(0);
}
pid3 = fork();
if (pid3 == 0)
{
printf("PID = %d, Parent PID = %d\n", getpid(), getppid());
pid5 = fork();
if (pid5 == 0)
{
printf("PID = %d, Parent PID = %d\n", getpid(), getppid());
pid6 = fork();
if (pid6 == 0)
{
printf("PID = %d, Parent PID = %d\n", getpid(), getppid());
sleep(30);
exit(0);
}
sleep(30);
exit(0);
}
sleep(30);
exit(0);
}
pid4 = fork();
if (pid4 == 0)
{
printf("PID = %d, Parent PID = %d\n", getpid(), getppid());
sleep(30);
exit(0);
}
sleep(30);
return 0;
}
每一个进程都会在退出前 sleep 30秒,从而保证能够用 ps 看到,
编译 gcc testpid.c -o testpid
然后执行,可以看到
PID = 24913
PID = 24914, Parent PID = 24913
PID = 24916, Parent PID = 24913
PID = 24915, Parent PID = 24913
PID = 24917, Parent PID = 24915
PID = 24918, Parent PID = 24917
ps -ef 的结果
24913 24582 0 11:29 pts/19 00:00:00 ./testpid
24914 24913 0 11:29 pts/19 00:00:00 ./testpid
24915 24913 0 11:29 pts/19 00:00:00 ./testpid
24916 24913 0 11:29 pts/19 00:00:00 ./testpid
24917 24915 0 11:29 pts/19 00:00:00 ./testpid
24918 24917 0 11:29 pts/19 00:00:00 ./testpid
#include <stdlib.h>
#include <unistd.h>
int main()
{
int pid1, pid2, pid3, pid4, pid5, pid6;
pid1 = getpid();
printf("PID = %d\n", pid1);
pid2 = fork();
if (pid2 == 0)
{
printf("PID = %d, Parent PID = %d\n", getpid(), getppid());
sleep(30);
exit(0);
}
pid3 = fork();
if (pid3 == 0)
{
printf("PID = %d, Parent PID = %d\n", getpid(), getppid());
pid5 = fork();
if (pid5 == 0)
{
printf("PID = %d, Parent PID = %d\n", getpid(), getppid());
pid6 = fork();
if (pid6 == 0)
{
printf("PID = %d, Parent PID = %d\n", getpid(), getppid());
sleep(30);
exit(0);
}
sleep(30);
exit(0);
}
sleep(30);
exit(0);
}
pid4 = fork();
if (pid4 == 0)
{
printf("PID = %d, Parent PID = %d\n", getpid(), getppid());
sleep(30);
exit(0);
}
sleep(30);
return 0;
}
每一个进程都会在退出前 sleep 30秒,从而保证能够用 ps 看到,
编译 gcc testpid.c -o testpid
然后执行,可以看到
PID = 24913
PID = 24914, Parent PID = 24913
PID = 24916, Parent PID = 24913
PID = 24915, Parent PID = 24913
PID = 24917, Parent PID = 24915
PID = 24918, Parent PID = 24917
ps -ef 的结果
24913 24582 0 11:29 pts/19 00:00:00 ./testpid
24914 24913 0 11:29 pts/19 00:00:00 ./testpid
24915 24913 0 11:29 pts/19 00:00:00 ./testpid
24916 24913 0 11:29 pts/19 00:00:00 ./testpid
24917 24915 0 11:29 pts/19 00:00:00 ./testpid
24918 24917 0 11:29 pts/19 00:00:00 ./testpid
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |