Home > OS >  Syntax error from running another file by exec (language C)(edit)
Syntax error from running another file by exec (language C)(edit)

Time:06-09

I'm experimenting with the family exec.

The first code is:

int main(int argc, char *argv[]){
    // Program changes permission because exec can't execute the file if permission is not accurated
    chmod("src2/child.c", S_IRWXU | S_IRWXU);

    // Now program creates one child process
    pid_t pid = fork();

    // If fork failed exit with error
    if (pid == -1)
    {
        perror("error in fork");
        exit(1);
    }
    if (pid == 0)
    {
        execlp("src2/child.c", "child.c", "Ciao");
        // if execlp return something is error
        perror("error in exec");
        exit(1);
    }
    // father exit
    exit(0);
}

The file child.c is:

int child(int argc, char *argv[])
{
    // write the term passed
    printf("%s\n", argv[1]);
    exit(0);
}

The makefile compiled both of the file. But in running, the terminal return 'src2/child.c: 6: Syntax error: "(" unexpected' I don't understand why

CodePudding user response:

Since src2/child.c isn't a binary and doesn't have a shebang (#!) line, the shell expects the file to contain shell commands to execute. But it does not.

You need to execute trygame (an executable), not src2/child.c (part of the source code used to create that executable).


You have previously shown that the C file in question is part of a project that includes a make file. This make file directs make to executes the following:

gcc -Wall -std=c99 -I./inc -c src/main.c      -o src/main.o
gcc -Wall -std=c99 -I./inc -c src/errExit.c   -o src/errExit.o
gcc -Wall -std=c99 -I./inc -c src/semaphore.c -o src/semaphore.o
gcc -Wall -std=c99 -I./inc -c src/child.c     -o src/child.o

gcc src/main.o src/errExit.o src/semaphore.o src/child.o -o trygame

This compiles four files found in src/ and links them into an executable named trygame.

You apparently renamed src to src2 and will need to adjust the make file accordingly. Once that's done, run make to generate the trygame executable.

To run the program, you need to execute this trygame, not src2/child.c.

  • Related