Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write the output of a process run using execl to a file in c

Tags:

c

file-io

I am writing a c program in which it calls a process using execl() function. I get the output of the process along with my c program output. I need to store the output of the process called using execl() to a file. I know programming basics and also file input and output.

Here is my program:

#include<stdio.h>
#include<unistd.h>
main()
{
printf("\nDisplaying output of ifconfig\n");
execl("/sbin/ifconfig","ifconfig",NULL);
}

Output:

Displaying output of ifconfig

eth1      Link encap:Ethernet  HWaddr 02:00:00:a1:88:21  
      ...........

lo        Link encap:Local Loopback  
      ........

I need to store the output of ifconfig in the file. How can i do it?

like image 881
Nithin Jose Avatar asked Jan 27 '26 03:01

Nithin Jose


1 Answers

You can use popen to run the program instead of calling execl, and read the out and write it to a file. Or use the system function, which invokes a shell and therefore can contain full shell redirection.

Or open the file using open and then use dup2 to redirect it to STDOUT_FILENO.

Actually, using the exec functions like that is highly unusual. Normally you create a new process and call exec in the child process.


Using open and dup2 is what I suggest in this case:

#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>

...

/* Open the file for writing (create it if it doesn't exist) */
int fd = open("/path/to/file", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP);

/* Make the standard output refer to the newly opened file */
dup2(fd, STDOUT_FILENO);

/* Now we don't need the file descriptor returned by `open`, so close it */
close(fd);

/* Execute the program */
execl("/sbin/ifconfig","ifconfig",NULL);

Note: I do not have any kind of error handling in the above code, which you should have.

like image 197
Some programmer dude Avatar answered Jan 29 '26 16:01

Some programmer dude