Tuesday, 10 June 2014

[Linux] system(3)

system(3) is a C library function and also can be used in perl.

SYNOPSIS in Perl

system LIST
system PROGRAM LIST

Description

  • system will do a fork first and then the parent will wait fro the child process, where the command is running on, to exit.
  • The return code from the command is got by wait(&ret) in parent process. An example of fork can be found by $man 2 wait.

    /**
     * wait(2)
     */
    #include <sys/wait.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <stdio.h>
    
    int main(int argc, char *argv[])
    {
        pid_t cpid, w;
        int status;
    
        cpid = fork();
        if (cpid == -1) { perror("fork"); exit(EXIT_FAILURE); }
    
        if (cpid == 0) {
            /* Code executed by child */
            printf("Child PID is %ld\n", (long) getpid());
            if (argc == 1)
                pause();                    /* Wait for signals */
            _exit(atoi(argv[1]));           /* exit code from child process */
        } else {
            /* Code executed by parent */
            do {    
                /* get exit code of child process in status */
                w = waitpid(cpid, &status, WUNTRACED | WCONTINUED); 
                if (w == -1) { perror("waitpid"); exit(EXIT_FAILURE); }
    
                if (WIFEXITED(status)) {
                    printf("exited, status=%d\n", WEXITSTATUS(status));
                } else if (WIFSIGNALED(status)) {
                    printf("killed by signal %d\n", WTERMSIG(status));
                } else if (WIFSTOPPED(status)) {
                    printf("stopped by signal %d\n", WSTOPSIG(status));
                } else if (WIFCONTINUED(status)) {
                    printf("continued\n");
                }
            } while (!WIFEXITED(status) && !WIFSIGNALED(status));
            exit(EXIT_SUCCESS);
        }
    }
        

  • The return code of system is exactly the same as status in above example. It's a 16-bit value with high 8-bit for exit code and low 8-bit for signal id. WEXITSTATUS just extracts exit code from status and like status >> 8.

  • use $man 3 system to get its reference in C and $perldoc -f system to get in perl.

  • See this link for more information

    http://perldoc.perl.org/functions/system.html

No comments :

Post a Comment