Difference between “system” and “exec” in Linux?

前端 未结 12 1901
天命终不由人
天命终不由人 2020-11-28 05:18

What is the difference between system and exec family commands? Especially I want to know which one of them creates child process to work?

12条回答
  •  眼角桃花
    2020-11-28 05:32


    int system(const char *cmdstring);
    

    Ex: system("date > file");


    In general, system is implemented by calling fork, exec, and waitpid, there are three types of return values.

    • If either the fork fails or waitpid returns an error other than EINTR, system returns –1 with errno set to indicate the error.
    • If the exec fails, implying that the shell can't be executed, the return value is as if the shell had executed exit(127).
    • Otherwise, all three functions—fork, exec, and waitpid—succeed, and the return value from system is the termination status of the shell, in the format specified for waitpid.

    The fork function is to create a new process (the child) that then causes another program to be executed by calling one of the exec functions. When a process calls one of the exec functions, that process is completely replaced by the new program, and the new program starts executing at its main function. The process ID does not change across an exec, because a new process is not created; exec merely replaces the current process—its text, data, heap, and stack segments—with a brand new program from disk.

    There are six different exec functions,


    int execl(const char *pathname, const char *arg0, ... /* (char *)0 */ );
    
    int execv(const char *pathname, char *const argv []);
    
    int execle(const char *pathname, const char *arg0, .../* (char *)0, char *const envp[] */ );
    
    int execve(const char *pathname, char *const argv[], char *const envp []);
    
    int execlp(const char *filename, const char *arg0,... /* (char *)0 */ );
    
    int execvp(const char *filename, char *const argv []);
    

提交回复
热议问题