用c语言编写程序,用fork

用c语言编写程序,用fork,第1张

唉,这种题目也就是教科书,大体思路就是记录fork的返回值

如果是0,那就是子进程,如果大于零就是进程本身,然后嵌套条件语句

#include <stdio.h>

#include <unistd.h>

void show (char *name) {

printf ("PID:%5u %s\n", getppid(), getpid (), name)

sleep (30)

}

int main () {

pid_t c1 = fork ()

if (-1 == c1)

perror ("fail to create child 1")

else if (0 == c1) {

show ("child1")

}

else {

pid_t c2 = fork ()

if (-1 == c2)

perror ("fail to create child 2")

else if (0 == c2) {

pid_t g1 = fork ()

if (-1 == g1)

perror ("fail to create child of child 2")

else if (0 == g1) {

pid_t gg1 = fork ()

if (-1 == gg1)

perror ("fail to create grand-child of child 2")

else if (0 == gg1) {

show ("grand-child of child 2")

}

else {

show ("child of child 2")

}

}

else {

show ("child2")

}

}

else {

pid_t c3 = fork ()

if (-1 == c3)

perror ("fail to create child 3")

else if (0 == c3) {

show ("child3")

}

else

show ("main")

}

}

}

编写一段程序,使用系统调用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!

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

#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://outofmemory.cn/yw/11842179.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-19
下一篇 2023-05-19

发表评论

登录后才能评论

评论列表(0条)

保存