【发布时间】:2020-04-29 10:00:56
【问题描述】:
我不知道,如果这样可以,但它编译:
typedef struct
{
int fd;
char *str;
int c;
} ARG;
void *ww(void *arg){
ARG *a = (ARG *)arg;
write(a->fd,a->str,a->c);
return NULL;
}
int main (void) {
int fd = open("./smf", O_CREAT|O_WRONLY|O_TRUNC, S_IRWXU);
int ch = fork();
if (ch==0){
ARG *arg; pthread_t p1;
arg->fd = fd;
arg->str = malloc(6);
strcpy(arg->str, "child");
arg->c = 6;
pthread_create( &p1, NULL, ww, arg);
} else {
write(fd, "parent\0", 7);
wait(NULL);
}
return 0;
}
我是父级的wait()int,但我不知道我是否也应该pthread_join 来合并线程,或者它是由wait() 隐含的。但是,在两个线程中写入同一个文件是否安全?我跑了几次,有时输出是 1)parentchild,但有时只有 2)parent,没有其他情况 - 我不知道为什么孩子在父母等待()时写得不好。有人可以解释为什么这些输出吗?
【问题讨论】:
-
贴出的代码无法处理调用
fork()失败的情况 -
这一行;
pthread_create( &p1, NULL, ww, arg);后面应该跟pthread_join( p1 );和exit( EXIT_SUCCESS ); -
关于这个参数:
S_IRWXU)X使输出文件可执行,这似乎有点过头了。 -
关于:
"parent\0"\0是一个 NUL 字节,编译器也会附加一个 NUL 字节。最后不需要一对 NUL 字节。 -
I/O 流
stdout被缓冲。数据仅在特定条件下传递到终端。强烈建议在每次调用write()后立即加上:fflush()声明。
标签: c multithreading io