
至于进程的上下文切换,一般情况下都不需要考虑它的性能消耗。不过在进程上下文切换次数较多的情况下(比如IO密集型系统),确实会对系统性能产生一定的影响。
代码没有问题,主要是while直接printf,时间太短,打屏输出速度跟不上,你看不到父进程输出,下面我修改了一下,增加了sleep,可以看到效果。#include<stdio.h>
#include<unistd.h>
#include<sys/wait.h>
using namespace std
int main(int argc, char *argv[])
{
int pid
pid = fork()
if(pid == 0)
{//子进程
while(1)
{
printf("child\n")
sleep(1)
}
}
else
{//父进程
while(1)
{
printf("parent\n")
sleep(1)
}
}
return 0
}输出结果:
parent
child
parent
child
parent
child
希望能帮助到你,你的好评是我前进的动力!谢谢!
你的问题其实很简单,就是一个多进程同步的问题, 解决同步问题有很多种方法,最常见的是用信号量,消息队列等。既然你题目要求使用pipe,我就在下面的例子中用pipe来实现。 思路很简单,通过两个pipe实现 父子进程间的同步, 父进程总是向第一个pipe写,从第二个pipe读,子进程相反。 当进程读到内容后,则它可以print,print完一个字符后,它写另一个pipe来通知另一个进程print。依次交替。在我的例子中,由父进程控制总共打印60个字符后结束(两个进程分别打印30次)。
这个例子很简单,就没什么需要再多解释的了,自己看吧,如果对这个例子还有什么不懂的,可以baidu hi我。 别忘加分, :)
#include <stdio.h>
#include <unistd.h>
/* delay 500ms for each print */
#define DELAY_TIME (1000*500)
int main()
{
int pid, i = 0, cmd
int p1[2], p2[2]
pipe(p1)
pipe(p2)
pid = fork()
if (pid >0)
{
/* parent */
close(p1[0])
close(p2[1])
for (i = 0i <30i++)
{
printf("%d", (i%10))
fflush(stdout)
usleep(DELAY_TIME)/* sleep to make print slow */
/* write to p1 to tell child continue */
cmd = i
write(p1[1], &cmd, sizeof(cmd))
/* read from p2 to wait for child complete */
read(p2[0], &cmd, sizeof(cmd))
}
/* -1 to tell child quit */
cmd = -1
write(p1[1], &cmd, sizeof(cmd))
wait(NULL)
printf("Parent done, quit...\n")
}
else
{
close(p1[1])
close(p2[0])
while(read(p1[0], &cmd, sizeof(cmd)) == sizeof(cmd)
&&cmd >= 0)
{
i = cmd
printf("%c", 'A'+(i%26))
fflush(stdout)
usleep(DELAY_TIME)/* sleep to make print slow */
/* write to p2 to tell parent continue */
write(p2[1], &cmd, sizeof(cmd))
}
printf("\n\nChild receive finish command from parent, quit...\n")
}
return 0
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)