2013-06-02 83 views
0

我学习Cfork(),我有这些错误:C:初始元素不是常数

app.c:13:1: warning: data definition has no type or storage class [enabled by default] 
app.c:13:1: error: initializer element is not constant 
app.c:15:1: error: expected identifier or ‘(’ before ‘if’ 
app.c:20:1: error: expected identifier or ‘(’ before ‘else’ 
app.c:26:1: error: expected identifier or ‘(’ before ‘else’ 

这里是源代码:

#include <sys/types.h> 
#include <sys/stat.h> 
#include <fcntl.h> 
#include <stdio.h> 
#include <stdlib.h> 

int f; 
pid_t pid; 

char msga[] = "abcd"; 
char msgb[] = "wxyz"; 

f = open("toto", O_WRONLY|O_TRUNC|O_CREAT,S_IRUSR|S_IWUSR); 

if ((pid = fork()) == -1) { 
    perror("fork"); 
    exit(EXIT_FAILURE); 
} 

else if (pid == 0) { 
    wait(NULL); 
    write(f, &msga, strlen(msga)); 
    close(f); 
} 

else { 
    wait(NULL); 
    write(f, &msgb, strlen(msgb)); 
    close(f); 
} 

回答

4

你需要用所有那个(在#include之后)函数里面!

int main(void) 
{ 
... 
} 

你可能要添加return 0;末那里。

在快速测试在这里,我还需要补充:

#include <unistd.h> 
#include <string.h> 

要获得fork(2)strlen(3)的声明,resepectively。