Search code examples
cshellcommand-linesystemexecute

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.


Solution

  • 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