简体   繁体   中英

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 ?

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.

It's not possible in Linux.

Allowing this could cause some subtle security bugs (remote code execution, destroying files of other users, etc.) and therefore is not allowed.

Instead, please just run the process under sudo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM