これは非常に単純なprogram.createパイプです。そしてfork、親プロセスと子プロセスの間のパイプを使用します。 となり、パイプへの書き込みはアトミックを保証しません。コードがパイプに書き込むと原子が確実に表示されないのはなぜですか?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
int main(void)
{
int pipe_fd[2];
pid_t pid;
char r_buf[4096];
char w_buf[4096*2];
int writenum;
int rnum;
memset(r_buf,0,sizeof(r_buf));
if(pipe(pipe_fd)<0) //create pipe
{
printf("pipe create error\n");
return -1;
}
if((pid=fork())==0) //fork
{
close(pipe_fd[1]);
while(1)
{
sleep(1);
rnum=read(pipe_fd[0],r_buf,1000);
printf("child: readnum is %d\n",rnum);
}
close(pipe_fd[0]);
exit(EXIT_SUCCESS);
}
else if(pid>0)
{
close(pipe_fd[0]);//write
memset(r_buf,0,sizeof(r_buf));
if((writenum=write(pipe_fd[1],w_buf,1024))==-1)
printf("write to pipe error\n");
else
printf("the bytes write to pipe is %d \n", writenum);
writenum=write(pipe_fd[1],w_buf,4096);
close(pipe_fd[1]);
}
return EXIT_SUCCESS;
}
result:
the bytes write to pipe 1000
the bytes write to pipe 1000 //show write pipe not atomic
the bytes write to pipe 1000
the bytes write to pipe 1000
the bytes write to pipe 1000
the bytes write to pipe 120 //show write pipe not atomic
the bytes write to pipe 0
the bytes write to pipe 0
......
それでは、私は、何故、atmoic meanを書いているのですか?そして、なぜこのプログラムがそれを示しているのですか?
私はあなたが何を求めているのかわからないし、あなたもどちらかと確信していません。一般的に原子性の概念に精通していますか? – duskwuff
あなたの出力はあなたのコードと一致せず、無意味です。 – ninjalj