中易网

c语言中创建子进程运行外部程序

答案:2  悬赏:60  
解决时间 2021-11-27 05:20
我想通过自己的程序启动一个外部程序(比如aaa.o),然后在某些条件下关闭这个程序。光用system()不够吧,应该要创建子进程吧?请教关键几步应该怎么写啊?
最佳答案
#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 int main() { int pid; pid=fork(); if(pid==0) printf("i am son,my pid is %d.\n",getpid()); else if(pid>0) { printf("i'm father ,my pid is %d.\n",getpid()); pid=fork(); if(pid==0) printf("i'm daughter process,my pid is %d.\n",getpid()); else if(pid>0) printf("i'm father process,my pid is %d.\n",getpid()); else printf("fork() error.\n"); } else printf("fork() error.\n"); }
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
入户的意思是什么?入户的释义是什么啊?
魔兽世界秘银外壳制作需要什么材料
典列的意思是什么啊?请解释下!
太仓同维电子有限公司,普工工资多少?
65岁的男人还有爱情吗
女朋友月收入4000,买个包却要1W2,我很不习
韩国济州岛今日天气预报5月5日
手机移动电玩城代理怎么做最新价格~
弹压的意思是什么?弹压的释义是什么啊?
女儿握着老妈妈的手致悼词
款矻的意思是什么啊?请解释下!
拉祜族真心爱你
意志的意思是什么?意志的释义是什么啊?
漂沫的意思是什么啊?请解释下!
桃仁里为什么有粘的东西
推荐资讯
业务员没有底薪合理吗
盛举的意思是什么啊?请解释下!
字符型常量在内存中存放的是?
大连北站之家酒店式公寓地址在什么地方,我要
广长舌的意思是什么啊?请解释下!
桄榔酒的意思是什么啊?请解释下!
1+(-2)+3+……+(-2012)
番鸭汤怎么做好吃,番鸭汤的吃法
甘肃省崇信县质量技术监督局地址在哪,我要去
请问有人把观音菩萨像遗弃在外面的关公石像下
三氧化二铁相对分子质量?组成元素的质量比?
您好 我刚生完宝宝。还没出月子,生宝宝时 侧
手机登qq时,显示手机磁盘不足,清理后重新登
刺客的套装怎么选啊?