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

Posted: May 28, 2012. At: 10:19 PM. This was 5 years ago. Post ID: 3946
Page permalink: http://securitronlinux.com/bejiitaswrath/running-a-command-within-another-program-how-to-do-this-with-c/

Now, we must convince Congress to stop the FCC. Can you display an alert?

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