用c语言编写一个程序实现以下功能

用c语言编写一个程序实现以下功能,第1张

#include "stdio.h"

int main(int argc,char *argv[]){

int a,b

double x,y

char ch1,ch2

printf("Please enter the data...\n")

scanf("%d%d%lf%lf %c%c",&a,&b,&x,&y,&ch1,&ch2)

printf("\na=%d,b=%d\nx=%f,y=%f\nch1=%c,ch2=%c\n",a,b,x,y,ch1,ch2)

return 0

}

运行样例:

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

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


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

原文地址: https://outofmemory.cn/yw/7698335.html

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

发表评论

登录后才能评论

评论列表(0条)

保存