What are some conditions that may cause fork() or system() calls to fail on Linux?

前端 未结 2 1718
礼貌的吻别
礼貌的吻别 2021-01-05 16:18

And how can one find out whether any of them are occuring, and leading to an error returned by fork() or system()? In other words, if fork() or system() returns with an err

2条回答
  •  我在风中等你
    2021-01-05 16:22

    nproc in /etc/security/limits.conf can limit the number of processes per user.

    You can check for failure by examining the return from fork. A 0 means you are in the child, a positive number is the pid of the child and means you are in the parent, and a negative number means the fork failed. When fork fails it sets the external variable errno. You can use the functions in errno.h to examine it. I normally just use perror to print the error (with some text prepended to it) to stderr.

    #include 
    #include 
    #include 
    
    int main(int argc, char** argv) {
        pid_t pid;
    
        pid = fork();
        if (pid == -1) {
            perror("Could not fork: ");
            return 1;
        } else if (pid == 0) {
            printf("in child\n");
            return 0;
        };
    
        printf("in parent, child is %d\n", pid);
    
        return 0;
    }
    

提交回复
热议问题