编写一个程序实现以下功能: (1)使用fork()创建进程。 (2)使用管道实现子进程和父进程之间的通信。

编写一个程序实现以下功能: (1)使用fork()创建进程。 (2)使用管道实现子进程和父进程之间的通信。,第1张

编写一段程序,使用系统调用fork( )创建两个子进程。当此程序运行时,在系统中有一个父进程和两个子进程活动。让仿哗橘每一个进程在屏幕上显示一个字符;父进程显示字符“a”,子进程分别显示字符“b”和“c”。试观察记录屏幕上的显示结果,并分析原因。

〈程序〉

#include<stdio.h>

main()

{

int p1,p2

if(p1=fork()) /*子进程创建成功*/

putchar('b')

else

{

if(p2=fork()) /*子进程创建成功*/

putchar('c')

else putchar('a'芦戚) /*父进程执行*/

}

}

<运行结果>

bca(有时会出现abc的任意的排列)

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

编制一段程序,实现进程的管道通信。使用系统调用pipe()建立一条管道线。两个子进程p1和p2分别向通道个写一句话:

child1 process is sending message!

child2 process is sending message!

而父进程则从管道中读出来自两个进程的信息,显示在屏幕上。

〈程序〉

#include <unistd.h>

#include <signal.h>

#include <stdio.h>

int pid1,pid2

main( )

{

int fd[2]

char outpipe[100],inpipe[100]

pipe(fd) /*创建一个管道*/

while ((pid1=fork( ))==-1)

if(pid1==0)

{

lockf(fd[1],1,0)

sprintf(outpipe,"child 1 process is sending message!")

/*把串放入数组outpipe中*/

write(fd[1],outpipe,50)/*向管道写长为50字节的串*/

sleep(5)/*自我阻塞5秒*/

lockf(fd[1],0,0)

exit(0)

}

else

{

while((pid2=fork( ))==-1)

if(pid2==0)

{

lockf(fd[1],1,0) /*互斥*/

sprintf(outpipe,"child 2 process is sending message!")

write(fd[1],outpipe,50)

sleep(5)

lockf(fd[1],0,0)

exit(0)

}

else

{

wait(0) /*同备团步*/

read(fd[0],inpipe,50) /*从管道中读长为50字节的串*/

printf("%s\n",inpipe)

wait(0)

read(fd[0],inpipe,50)

printf("%s\n",inpipe)

exit(0)

}

}

}

〈运行结果〉

延迟5秒后显示:

child1 process is sending message!

再延迟5秒:

child2 process is sending message!

附:我承认我是复制的 不过很符合题意~

看我下面的程序,子进程每两秒钟打印一次 Child print xxx

父进程fork子进程10秒后,向子进程发 SIGSTOP信号,让其停止运行。 再过5秒后,发 SIGCONT 让子进程恢复执行。再过20秒后,杀掉子进程,父进程也结束。还有疑问,可以baidu hi我,记得散闭加分吧。

#include <sys/types.h>

#include <signal.h>

#include <stdio.h>

#include <unistd.h>

void child_process()

{

int i = 0

printf("Child start...\n")

while(1)

{

sleep(2)

printf("Child print %d\n", ++i)

}

}

int main()

{

int pid

printf("Fork child process ...\n")

sleep(1)

pid = fork()

if (pid >0)

{

printf("This is parent process, I will stop child process ~10 seconds later...\n")

sleep(10)

printf("Stop child process\n")

kill(pid, SIGSTOP)

printf("掘蔽I will wake up child process 5 seconds later...\n")

sleep(5)

printf("Wake up child process\n")

kill(pid, SIGCONT)

/* after 20 seconds, kill child */

sleep(20)

kill(pid, SIGKILL)

wait(NULL)

printf("Bye\n"冲散裂)

}

else

{

child_process()

}

return 0

}

#include <stdio.h>

#include <stdlib.h>脊明虚

#include <sys/types.h>槐带

#include <unistd.h>

int main()

{

int p1,p2

if(p1=fork())

{

printf("I am child 1。\n")

fork()

}

else

{

if(p2=fork()) printf("I am child 2。\樱燃n")

else printf("I am parent。\n")

}

return 0

}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/yw/12494696.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2025-08-25
下一篇2025-08-25

发表评论

登录后才能评论

评论列表(0条)

    保存