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

Posted: May 28, 2012. At: 10:19 PM. This was 6 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.

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.

No comments have been made. Use this form to start the conversation :)

Leave a Reply