#include <sys/types.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> int glob=6; char buf[]="a write to stdout "; int main (void) { int var; pid_t pid; var=88; if(write(STDOUT_FILENO,buf,sizeof(buf)-1)!=sizeof(buf)-1) // err_sys("write error"); printf("before fork "); if((pid=fork())<0) // err_sys("fork error"); {printf("fork error"); } else if(pid==0) { glob ; var ; } else sleep(2); 结果如下: [root@localhost ~]# gcc 8-1.c -o 8-1 [root@localhost ~]# ./8-1 a write to stdout pid=5674,glob=7,var=89 pid=5673,glob=6,var=88 [root@localhost ~]# ./8-1 > ./temp [root@localhost ~]# cat ./temp a write to stdout pid=5678,glob=7,var=89 pid=5677,glob=6,var=88 中途出现 8-1.c: In function ‘main’: 8-1.c:20: 错误:expected expression before ‘else’ 原因: if后面的语句要用一对大括号括起来,因为if只管后面一句语句如果不用大括号括起来的话,相当于if语句已经结束,这时你再加个else,则编译器认为没有合适if语句来匹配else解决办法:在 if 后加个 {} 内容随意 不影响即可 头文件#include <unistd.h>内 定义了 STDOUT_FILENO
|
|