-
dup2 prob
Actually the title is a little misleading butthat is where the problem occurs. Those of you familiar with unix should know what I'm talking about.
Basically I'm using dup2() to redirect ouput meant for stdout to a file using the top command the problem is that the process hangs. I've guessed that top's not releasing the file descriptor once it's done (I'm passing it the instruction to dump just once into the file) but that's just a guess.
Now advanced unix-ers, please correct me if I'm wrong on this but with using the dup2() command I don't need to save the stdout file descriptor before I redirect it to the file which means when I'm done and I close it stdout should be returned to normal ops.
For those of you wanting to run the code, I attached it to my post in the networking board (should be on 1st page as it's recent)
Thanx for your time.
-
> dup2(fd, STDOUT);
If you're trying to make stdout go to the file fd refers to, then its
dup2(STDOUT,fd);
> I attached it to my post in the networking board
Pasting a URL would be a great help in future
http://cboard.cprogramming.com/showthread.php?t=63790
-
thanx for the reply. Basically I'm trying to redirect everything meant for standard output to a file. I tried the correction you gave it doesn't store to the file.
-
> if ((execl("/usr/bin/top","-b", "-n", "1", NULL)) < 0)
You missed off argv[0] (which is currently -b)
if ((execl("/usr/bin/top","/usr/bin/top","-b", "-n", "1", NULL)) < 0)
-
Thanx man that did the trick but I have a slight problem. There is a work around but it's not efficient.
Code:
if (fork() == 0)
{
if ((fd = open(fdump, O_CREAT | O_RDWR, 0660)) < 0)
fprintf (stderr,"ERROR(opening file): %s.\n", strerror(errno));
dup2(fd, STDOUT);
if ((execl("/usr/bin/top", "/usr/bin/top","-b", "-n","1", NULL)) < 0)
fprintf (stderr,"ERROR(execl): %s.\n", strerror(errno));
close(fd);
read(fd, tmpBUF, msgSZ); <--------------- I don't seem to be getting here at all.
printf("before piping: %s./n/n", tmpBUF);
close(pd[READ]); //close read end of the pipe
write(pd[WRITE], tmpBUF, strlen(tmpBUF));
//printf("Sent to Parent: %s.\n", );
close(pd[WRITE]); //close write end
close(fd);
exit(0);
I can't get the print out of the buffer before send the contents to the parent. In fact after that execl() command it exits prematurely to the parent.
-
You do know what execl() does right?
It replaces the CURRENT process with a NEW process.
Any statements after a successful execl() call do not happen.
-
Thought so. I wasn't sure whether when it exits it takes the child with. But thanx for re-affirming my suspicions