How To Execute A Shell Script From C in Linux - Stack Overflow
How To Execute A Shell Script From C in Linux - Stack Overflow
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
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
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