sherinkapotein sherinkapotein - 1 year ago 78
C Question

C-Passing arguments for execution of a program in new Xterm window

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

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
printf("insufficient parameters\n");
return 0;


And another program,
which, during the course of its execution is required to call
and make it display in a new xterm/gnome-terminal window.

int main()
char buf[25]="Test String";//as argument for program to be called
int pid_child=fork();
printf("Fork Failed. Exiting");


int status=0;

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

-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

Answer Source

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().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download