简体   繁体   中英

execute shell command with sudo in c program

What is the best way to execute this command: "sudo cat /var/log/auth.log | grep Accepted" inside my C program ? I tried to use:

sprintf(command_result,"sudo cat /var/log/auth.log | grep Accepted"); 

But it didn't work obviously.

You cannot execute the command with sprintf() you need system() atleast

fix:

sprintf(command_result, "sudo cat /var/log/auth.log | grep Accepted");
system(command_result);

you can execute the command with pipe

FILE *fp;
fp=popen(command_result,"r");

and then you can read the command output from the pipe fp like you read from files with fgets() or fread() ...

BTW you can not execute sudo command if the password is required in the sudo command

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