0

I'm a beginner to systems programming and I am currently trying to play around with basic server/client communication using sockets, pipes, etc

More specifically I want to be able to connect as a client and input something like '/bin/echo hello'. The server will then split the string into the command and its arguments, and run the command with a call to a function that calls execl(). For now I'm just testing exec call before trying to pass user input in. Why does the following fail with errno set to EFAULT: bad address?

int do_command(char *command) {
    if(strcmp(command, "some_string") == 0) {
        pid_t pid = fork();
        if(pid == -1) {
            perror("fork");
            exit(1);
        }
        if(pid == 0) {
            if (execl("/bin/echo", "/bin/echo/", "hello", (char*)NULL) == -1) {
                perror("execl");
                exit(1);
            }           
        } else {
            printf("parent\n");
        }
    }
}

But running the same code in main() runs just fine with an output of 'hello'

int main() {
        pid_t pid = fork();
        if(pid == -1) {
            perror("fork");
            exit(1);
        }
        if(pid == 0) {
            if (execl("/bin/echo", "/bin/echo/", "hello", (char*)NULL) == -1) {
                perror("execl");
                exit(1);
            }           
        } else {
            printf("parent\n");
        }
}

Is it not possible to run exec() system calls within functions? Thanks in advance.

  • 6
    The only difference is the `strcmp`, and the fact that you didn't show us a complete program. See [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) in the [help center](https://stackoverflow.com/help). – user3386109 Apr 03 '18 at 05:35
  • 3
    "Is it not possible to run exec() system calls within functions? Thanks in advance." - definitly should be possible to do, as is the case with all system calls. Like @user3386109 commented - shoiw us your complete code. An important piece of this puzzle is missing. – Rann Lifshitz Apr 03 '18 at 05:38
  • Your function has undefined behaviour because it doesn't return a value. (May or may not be related to this specific error). – n. m. could be an AI Apr 03 '18 at 05:41
  • If you call `do_command("some_string")`, it should execute the `echo` command. If you call it some other how (for example, after reading the string/line with `fgets()` and forgetting to remove the newline, and/or leading and trailing white space), then it won't work. But there are major differences between your code in the sample `main()` and the function — related to the string comparison – so that is almost definitively where you've got problems. – Jonathan Leffler Apr 03 '18 at 06:21

0 Answers0