I’m trying to execute other programs within my C program. My first attempt was with popen. When I try to read from pipe I only get a reply of 1 byte and nothing in buf. I’m not sure as to the reasoning behind this.
popen example:
#include<stdio.h>
#include<unistd.h>
int main(int argc, char* argv[])
{
FILE* pipe;
if ((pipe=(FILE*)popen("./test.php","r"))==NULL)
printf("this is not working\n");
char buf[1024] = {'\0'};
int fd=fileno(pipe);
int bytes = read(fd, buf, 1024);
printf("bytes read %d\n", bytes);
printf("The program: %s\n", buf);
if(pclose(pipe)<0)
printf("not working\n");
return 0;
}
php example
#!/usr/bin/php
<?php
echo "THIS IS A TEST THAT WORKED\n";
?>
The output:
bytes read 1
The program:
The output of ls:
ls -l test.php
-rwxr-xr-x+ 1 tpar44 user 62 Nov 10 14:42 test.php
Any help in this would be greatly appreciated!
Thanks!
You need to execute the php interpreter and pass the name of the script as argument, when using
popenif your script does not have the shebang because the shell won’t know which interpreter to use:If the script has the shebang line you can just execute it, because
popenuses the shell to execute commands and it can find out which one to use, so you could just do this:However, make sure the script is executable:
you could also use
execl()but you have to specify the path to the binary becauseexecldoesn’t use the shell:Don’t forget to actually read from the pipe 😉