System and popen system call
From Teknologisk videncenter
System executes a shell command
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int main(void) {
5 if (system("/usr/bin/date")) // Always use a full or a relative path!!!
6 fprintf(stderr,"ERROR: %m\n");
7
8 return(0);
9 }
Security issue
As system() searches through $PATH to find the executable file - it is possible to put an executable with the same name earlier in $PATH and run a bogus and evil program.
Make your own system() function
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <sys/types.h>
4 #include <unistd.h>
5 #include <wait.h>
6 #include <errno.h>
7
8 int my_system(const char *command) {
9 int wstatus;
10 int pid;
11
12 if (command[0] != '/') {
13 errno=EPERM;
14 return(EPERM);
15 }
16 if ((pid=fork()) == 0) { // Child
17 execl("/bin/sh", "sh", "-c", command, (char *) NULL);
18 return(0);
19 } else {
20 if (pid < 0) // fork failed
21 return(pid);
22 if (pid > 0) { //Parent
23 while(wait(&wstatus) > 0);
24 return(0);
25 }
26 }
27 }
28
29 int main(void) {
30 if (my_system("date"))
31 fprintf(stderr,"ERROR: %m\n");
32 if (my_system("/usr/bin/date"))
33 fprintf(stderr,"ERROR: %m\n");
34 return(0);
35 }