c++clinuxfile-permissionschown

How to create file as another user via C/C++ in Linux?


Linux C/C++ has open or fopen API, but created file are belong to process uid.

If we want to change owner/group of this file, we can use chown or fchown API after file created.

But, is there one API for creating file as another user, not two API ?


Solution

  • There is no Unix api dedicated for that, but you can change the current user to other user before create the file, such as:

    1. Make sure you have permission. The current effective user must be "root" OR set user or group ID on executable file.

    2. Call setgid and setuid to other user.

    3. Create the file.

    4. Call setuid and setgid to old user if required.

    Because the user is process-wide, if your program is multi-threaded, you may need to fork a child process doing the steps I listed before.

    But if you want non-root user (such as nobody) to run your program, you can give the permission to your executable file:

    sudo chown root:root ./your_app && sudo chmod gu+s ./you_app
    

    Now you can call setuid(0) and setgid(0) to acquire root permission.