Difference between revisions of "System and popen system call"
From Teknologisk videncenter
(Created page with " System executes a shell command <source lang=c line> #include <stdio.h> #include <stdlib.h> int main(void) { if (system("/usr/bin/date")) // Always use a full or a relati...") |
(No difference)
|
Revision as of 12:53, 19 December 2022
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
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
9 int my_system(const char *command) {
10 int wstatus;
11 int pid;
12
13 if (command[0] != '/') {
14 errno=EPERM;
15 return(EPERM);
16 }
17
18 if ((pid=fork()) == 0) { // Child
19 execl("/bin/sh", "sh", "-c", command, (char *) NULL);
20 return(0);
21 } else {
22 if (pid < 0) // fork failed
23 return(pid);
24 if (pid > 0) { //Parent
25 while(wait(&wstatus) > 0);
26 return(0);
27 }
28 }
29 }
30
31
32 int main(void) {
33 if (my_system("date"))
34 fprintf(stderr,"ERROR: %m\n");
35 if (my_system("/usr/bin/date"))
36 fprintf(stderr,"ERROR: %m\n");
37 return(0);
38 }