0% found this document useful (0 votes)
248 views

How To Execute A Shell Script From C in Linux - Stack Overflow

The document discusses several ways to execute a shell script from C code in Linux, including using the system() library function, popen()/pclose() to set up pipes, or fork() and execve() system calls directly. Forking and execve() allows more fine-grained control and avoids having the shell run the command twice. An example is provided using fork(), pipe(), and execlp() to execute a shell script and capture its output.

Uploaded by

Ias Aspirant
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
248 views

How To Execute A Shell Script From C in Linux - Stack Overflow

The document discusses several ways to execute a shell script from C code in Linux, including using the system() library function, popen()/pclose() to set up pipes, or fork() and execve() system calls directly. Forking and execve() allows more fine-grained control and avoids having the shell run the command twice. An example is provided using fork(), pipe(), and execlp() to execute a shell script and capture its output.

Uploaded by

Ias Aspirant
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

10/24/2015

HowtoexecuteashellscriptfromCinLinux?StackOverflow

signup

login

tour

StackOverflowisacommunityof4.7millionprogrammers,justlikeyou,helpingeachother.Jointhem,itonlytakesaminute:

help

stackoverflowcareers

Signup

HowtoexecuteashellscriptfromCinLinux?

HowcanIexecuteashellscriptfromCin
Linux?
c linux shell

askedSep17'10at14:29
FairDinkumThinkum
5,165

13

42

95

5Answers

Itdependsonwhatyouwanttodowiththescript(oranyotherprogramyouwanttorun).
Ifyoujustwanttorunthescript system istheeasiestthingtodo,butitdoessomeotherstufftoo,
includingrunningashellandhavingitrunthecommand(/bin/shundermost*nix).
Ifyouwanttoeitherfeedtheshellscriptviaitsstandardinputorconsumeitsstandardoutputyou
canuse popen (and pclose )tosetupapipe.Thisalsousestheshell(/bin/shundermost*nix)
torunthecommand.
Bothofthesearelibraryfunctionsthatdoalotunderthehood,butiftheydon'tmeetyourneeds
(oryoujustwanttoexperimentandlearn)youcanalsousesystemcallsdirectly.Thisalso
allowsyoudoavoidhavingtheshell(/bin/sh)runyourcommandforyou.
Thesystemcallsofinterestare fork , execve ,and waitpid .Youmaywanttouseoneofthe
librarywrappersaround execve (type man3exec foralistofthem).Youmayalsowanttouse
oneoftheotherwaitfunctions( man2wait hasthemall).Additionallyyoumaybeinterestedin
thesystemcalls clone and vfork whicharerelatedtofork.
fork duplicatesthecurrentprogram,wheretheonlymaindifferenceisthatthenewprocess
gets0returnedfromthecalltofork.Theparentprocessgetsthenewprocess'sprocessid(oran
error)returned.
execve

replacesthecurrentprogramwithanewprogram(keepingthesameprocessid).

waitpid

isusedbyaparentprocesstowaitonaparticularchildprocesstofinish.

Havingtheforkandexecvestepsseparateallowsprogramstodosomesetupforthenew
processbeforeitiscreated(withoutmessingupitself).Theseincludechangingstandardinput,
output,andstderrtobedifferentfilesthantheparentprocessused,changingtheuserorgroupof
theprocess,closingfilesthatthechildwon'tneed,changingthesession,orchangingthe
environmentalvariables.
Youmayalsobeinterestedinthe pipe and dup2 systemcalls. pipe createsapipe(withboth
aninputandanoutputfiledescriptor). dup2 duplicatesafiledescriptorasaspecificfile
descriptor( dup issimilarbutduplicatesafiledescriptortothelowestavailablefiledescriptor).
answeredSep17'10at15:15
nategoose
8,772

11

27

It'salsoworthnotingthatfork()isquitecheapsincethememoryiscopyonwriteandnotduplicatedas
soonastheprogramforks.CercerillaSep17'10at15:33
I'mabigfanoffork/execitletsyouavoidenvironmentbaseduncertaintlyaboutwhat'sgoingtorun.But
canyouuseitonshellscriptsdirectly?Asyousay,byusingexec,you"avoidhavingtheshell(/bin/sh)run

http://stackoverflow.com/questions/3736210/howtoexecuteashellscriptfromcinlinux

1/3

10/24/2015

HowtoexecuteashellscriptfromCinLinux?StackOverflow

yourcommandforyou"don'tyouthusneedtoexec/bin/shtorunashellscript?TomAndersonSep17
'10at16:33
1 @TomAnderson:Iftheshellscripthasexecutionpermissionssetfortheeffectiveuserandhasan
appropriateshabangfirstlinelistingafilewhichtheeffectiveuseralsohaspermissiontoexecuteandalso
isnotitselfascriptofsomesortthenthekernelwillcallthefilelistedontheshabanglinewiththescript
file.Ifthescript'sshabangwere #!/bin/csh then /bin/sh wouldnotberuninthefork/execscenario.If
itwere #!/bin/sh thenitwouldinthefork/execscenario,butwiththe system version /bin/sh would
beruntwiceforthisscript.nategooseSep17'10at16:43

Youcanuse

system

system("/usr/local/bin/foo.sh");

Thiswillblockwhileexecutingitusing

shc

,thenreturnthestatuscode.

editedSep17'10at14:35

answeredSep17'10at14:30
MatthewFlaschen
155k

22

323

426

1 +1Don'tforgettoinclude <stdlib.h> (linux.die.net/man/3/system)pmgSep17'10at14:34


1 ...assumingithasexecutablebitandshebangline.Ingeneral, system("/bin/sh
/usr/local/bin/foo.sh"); .Yes,thisactuallycallstheshelltwice. RomanCheplyaka Sep17'10at
15:07

Ifyou'reokwithPOSIX,youcanalsouse

popen()

pclose()

#include<stdio.h>
#include<stdlib.h>
intmain(void){
/*lsal|grep'^d'*/
FILE*pp;
pp=popen("lsal","r");
if(pp!=NULL){
while(1){
char*line;
charbuf[1000];
line=fgets(buf,sizeofbuf,pp);
if(line==NULL)break;
if(line[0]=='d')printf("%s",line);/*lineincludes'\n'*/
}
pclose(pp);
}
return0;
}

editedMay12at14:11

answeredSep17'10at14:59
pmg
61.9k

Ifyouneedmorefinegradecontrol,youcanalsogothe fork pipe


yourapplicationtoretrievethedataoutputtedfromtheshellscript.

exec

editedSep17'10at14:42

69

121

route.Thiswillallow

answeredSep17'10at14:33
doron
12.1k

22

58

Ipreferfork+execlpfor"morefinegrade"controlasdoronmentioned.Examplecode
shownbelow.
Storeyoucommandinachararrayparameters,andmallocspacefortheresult.
intfd[2];

http://stackoverflow.com/questions/3736210/howtoexecuteashellscriptfromcinlinux

2/3

10/24/2015

HowtoexecuteashellscriptfromCinLinux?StackOverflow

pipe(fd);
if((childpid=fork())==1){
fprintf(stderr,"FORKfailed");
return1;
}elseif(childpid==0){
close(1);
dup2(fd[1],1);
close(fd[0]);
execlp("/bin/sh","/bin/sh","c",parameters,NULL);
}
wait(NULL);
read(fd[0],result,RESULT_SIZE);
printf("%s\n",result);

answeredMay12at11:00
GABIKA6
71

http://stackoverflow.com/questions/3736210/howtoexecuteashellscriptfromcinlinux

3/3

You might also like