題目:
編寫一個程序,開啓2個進程,一個進程負責輸出字符A,一個進程負責輸出字符B,要求輸出結果爲ABABAB… 依次遞推。
環境:Ubuntu+Codeblocks
首先是我寫的:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid;
char c;
pid=fork();
if(-1 == pid){
printf("Process creation failed.\n");
return -1;
}
else if(pid == 0){
c = 'B';
}
else{
c = 'A';
}
//circle
while(1){
printf("%c",c);
fflush(stdout);
sleep(1);
}
return 0;
}
老師評語:打印可能正確,但沒有用到管道,不完美。
然後是標準答案:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
int fd[2];
pid_t pid;
pipe(fd);
pid = fork();
if( 0 == pid)
{
close(fd[0]);
while(1)
{
printf("A\n");
write(fd[1],"A",1);
sleep(1);
}
}
else
{
close(fd[1]);
char c;
while(1)
{
read(fd[0],&c,1);
printf("B\n");
}
}
return 0;
}
多寫多練加油!!