Reputation: 47
Problem statement:-
How to pass arguments to a program for execution in a new Xterm/Gnome window which will be calling through execlp.
A little elaborate explanation:-(oxymoron eh?)
Consider the following program which will take a string as argument and display it
//output.c
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
if(argc<2)
{
printf("insufficient parameters\n");
exit(1);
}
printf("%s",argv[1]);
sleep(10);
return 0;
}
And another program,client.c
which, during the course of its execution is required to call output.c
and make it display in a new xterm/gnome-terminal window.
//client.c
int main()
{
char buf[25]="Test String";//as argument for program to be called
int pid_child=fork();
if(pid_child==-1)
{
printf("Fork Failed. Exiting");
exit(1);
}
if(pid_child==0)
{
execlp("/usr/bin/xterm","-e","./output",buf,NULL);
}
int status=0;
while(wait(&status)!=-1);
}
The line of contention here is
execlp("/usr/bin/xterm","-e","./output",buf,NULL); //With string `buf` as argument for `output`.
Result:-Does not run
Error -e: Explicit shell already was /~/cs60/directory/./output
-e: bad command line option "Test String"
execlp("/usr/bin/xterm","-e","./output",NULL);//Without passing variable `buf`
Result:- a) New Xterm window opens. b) output terminates with Insufficient parameters (as expected).
The manpage clearly states for Xterm:
-e program [ arguments ... ]
This option specifies the program (and its command line arguments) to be run in the xterm window.
It works perfectly fine when I run it from a terminal (as a script). But how can I achieve this through C.
Any help will be highly appreciated
Upvotes: 1
Views: 2730
Reputation: 56
You need to understand how execlp()
works.
You need to add a second argument to execlp
with the command name ("xterm").
execlp("/usr/bin/xterm", "xterm", "-e", "./output", buf, NULL);
Also, your output program may want to do a fflush
(so you see the output), and you should exit or otherwise take proper evasive action if execl()
fails. Note that when the command name ("/usr/bin/xterm"
) contains any slashes, execlp()
behaves the same as execl()
.
Upvotes: 3