Reputation: 133
I have written a small code which takes input from the user and passes it to the system ("command>/tmp/j"), here the file j is being created but there is no information inside it related to the input present in the command. For eg: If I have given ps -f as input to the string command, the system() should execute it and store it inside file /tmp/j, but here the file j is being created but there is no output data inside it.
I have seen many questions, but all those are using popen() and the input is predefined in them.
#include<stdio.h>
#include<sys/syscall.h>
main()
{
enum msgtype {PROCESS_LIST_REQUEST=1, PROCESS_LIST_RESPONSE, DIRECTORY_LIST_REQUEST, DIRECTORY_LIST_RESPONSE, ERROR_REQUEST};
struct head
{
int version;
int msg_length;
int header_length;
enum msgtype msg_type;
char data;
char *reqtype;
};
struct head *buf;
buf = malloc((sizeof(struct head)));
buf->reqtype=malloc(40);
char req[10];
char *command;
command = malloc((sizeof(char) * 10));
fgets(req, sizeof(req),stdin);
buf->reqtype = req;
printf("%s" , buf->reqtype); //just to make sure correct thing is present
command = buf->reqtype;
printf("%s",command);//just to make sure correct thing is present
system ("command>/tmp/j");
{
FILE *fp;
char c;
fp = fopen("/tmp/j", "r");
if (fp == NULL)
printf("File doesn't exist\n");
else {
do {
c = getc(fp);
putchar(c);
} while (c != EOF);
}
fclose(fp);
}
}
Upvotes: 0
Views: 63
Reputation: 50120
As somebody else says
system ("command>/tmp/j");
tries to run a program called 'command'. YOu need to do
char buff[256];
snprintf(buff, sizeof(buff), "%s>/tmp/j", command);
system(buff);
Upvotes: 0
Reputation: 1
This line
system ("command>/tmp/j");
Tries to run an executable literally called command
, and redirects its output to /tmp/j
. The redirection happens, thus creating the file /tmp/j
, but then command
(whatever it may be) produces no output.
Also, this
command = malloc((sizeof(char) * 10));
followed by this
command = buf->reqtype;
causes the memory from the malloc()
call to leak.
Upvotes: 1