书上抄了一个fork系统调用讲解的例子,代码如下:
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/uio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char buf[100] = {0};
pid_t cld_pid;
int fd;
int status;
if((fd = open("temp", O_CREAT | O_RDWR | O_TRUNC, 0664)) == -1)
{
perror("创建文件");
exit(1);
}
strcpy(buf, "父进程数据");
if((cld_pid = fork()) == 0)
{
strcpy(buf, "子进程数据");
puts("子进程正在工作:");
printf("子进程 PID 是%d\n",getpid());
printf("父进程 PID 是%d\n",getppid());
write(fd, buf, strlen(buf));
close(fd);
exit(0);
}
else
{
puts("父进程正在工作:");
printf("父进程 PID 是%d\n", getppid());
printf("子进程 PID 是%d\n", getpid());
write(fd, buf, strlen(buf));
close(fd);
}
wait(&status);
return 0;
}
编写结束,运行gcc -o fork_test fork_test.c,就是报错
/usr/bin/ld: cannot open output file fork_test: Is a directory
collect2: ld 返回 1
代码检查了好几次都没有Wen题,百度也百思不得其解。
打算删除代码Wen件夹时,发现fork_test.c没有存到fork_test wen件夹中(他俩同时出现在一个目录中),顺手放进去又编译了一次,居然通过了。
父进程正在工作:
父进程 PID 是7412
子进程 PID 是7493
子进程正在工作:
子进程 PID 是7494
父进程 PID 是7493
原因不知Wei什么?至少是个教训。