Search code examples
linuxnginxfilesystemsforkpermission-denied

Why does child process get 13(Permission denied) when open the file created by parent process in nginx


I am trying to write a plugin in nginx, I should create a file in main process then child process will read this file. I have set the file 0766 in main process, but open and statvfs failed when I try to open the file in child process, the errno is 13 which means Permission denied.

Is there any special settings between parent and child processes? How can I solve it?

my code is like this:

// in nginx main process I create the file
u_char* shared_addr = NULL; 
int map_my_file(const char* path)
{
    extern int errno;
    umask(0);
    int fd = open(path, O_RDWR | O_CREAT | O_EXCL, 0766);
    if (fd < 0)
    {
        ngx_log_stderr(0, "open file failed %s, %d", path, errno);
    }
    if (ftruncate(fd, 1024 *1024) < 0)
    {
        printf("ftruncate %d failed", fd);
    }
    shared_addr = (u_char*)mmap(NULL, 1024 * 1024, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    close(fd);
}

// in nginx child process, I try to open the file 
    int cfd = 0;
    if ((cfd = open("./t.log", O_RDWR)) >= 0)
    {
        printf("child open success\n");
    } else {
        printf("failed %d\n", errno);
    }
// I got `failed 13`, means `Permission denied`

If I take these create and open codes out separately and put them in a sample parent-child process case, it can works correctly. But it can not work in nginx, always told me 13.


Solution

  • There are two reasons lead to this error

    1. I did not set user in nginx.conf, thus nobody will control the work process in default according this, Nginx will set user when child process initializes.

    2. The child process needs x access on all directories, see this.

    Check the following:

    chmod +x /home/
    chmod +x /home/username
    chmod +x /home/username/siteroot