Posted: . At: 10:19 PM. This was 12 years ago. Post ID: 3946
Page permalink. WordPress uses cookies, or tiny pieces of information stored on your computer, to verify who you are. There are cookies for logged in users and for commenters.
These cookies expire two weeks after they are set.


Running a command within another program. How to do this with C.


This code snippet will run the date command. The execl() function is very useful for executing a command within your C program.You replace the NULL identifiers with any extra arguments to pass to the program. I prefer this over the system() function.

#include <unistd.h>
 
int main(void) {
 
	execl("/bin/date", "%c", NULL, NULL, NULL);
	return 0;
}

Just compile this example.

localhost% cc exec.c

And then run it to get the date.

localhost% ./a.out 
Thu May 25 10:03:37 AEST 2017

The system() function would be used this way. It is a little simpler to use.

#include <stdio.h>
 
int main (void)
{
	system("date +%s");
}

The man execl command on Linux will bring up some more information about using the various related functions for executing another program within your C program.


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.