C:初始化元素不是常量

时间:2013-06-02 21:46:55

标签: c io fork element

我正在fork()中学习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);
}

1 个答案:

答案 0 :(得分:4)

你需要在函数内包装所有这些(在#include行之后)!

int main(void)
{
 ...
}

您可能也希望在那里添加return 0;

在这里的快速测试中,我还需要添加:

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

分别获取fork(2)strlen(3)的声明。