Multiple reads and writes with popen?

Joined
Jul 9, 2008
Messages
1
Reaction score
0
Hi,

I am trying to create an interactive shell inside a C program.

I call popen to get a file pointer which also invokes a shell. I pass a command to that and then use fgets to get the reply back from the shell. I leave the pointer open for a subsequent command. When I want to do another command I use fputs to send it the command line, but I get an error code of 5 back when I do so. Any further interaction with the file pointer yields a SIGPIPE.

Code is below.

Can anyone tell me what the proper way is to, in C, create a shell and issue multiple commands and receive output from those?

Thanks!

- (char*)doShell:(char*) cmd
{
int resultCode = 0;
char* rValue;
char* dataR = (char*)malloc(cCMDReturnBufSize);
char* dataOff = dataR;

if (dataR == NULL)
dataR = (char*)malloc(cCMDReturnBufSize);

if (fp == NULL)
fp = popen(cmd, "r+");
else
{
resultCode = fputs(cmd, fp);
}

fprintf("result code %i\n", resultCode);

// Should REALLY check the output for error.

do
{
rValue = fgets(dataOff, cCMDReturnBufSize, fp);

if (rValue != NULL)
{
dataOff += strlen(rValue);
}


} while ((rValue != NULL) && ((dataOff-dataR) < cCMDReturnBufSize)); // Proceed as long as there is more data, or our buffer is full

return dataR;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top