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...") |
m (→Make your own system) |
||
Line 22: | Line 22: | ||
#include <wait.h> | #include <wait.h> | ||
#include <errno.h> | #include <errno.h> | ||
− | |||
int my_system(const char *command) { | int my_system(const char *command) { | ||
Line 32: | Line 31: | ||
return(EPERM); | return(EPERM); | ||
} | } | ||
− | |||
if ((pid=fork()) == 0) { // Child | if ((pid=fork()) == 0) { // Child | ||
execl("/bin/sh", "sh", "-c", command, (char *) NULL); | execl("/bin/sh", "sh", "-c", command, (char *) NULL); | ||
Line 45: | Line 43: | ||
} | } | ||
} | } | ||
− | |||
int main(void) { | int main(void) { |
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 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 }