-1
#include <unistd.h>
#include <sys/types.h> 
#include <sys/wait.h>
#include <stdlib.h>
#include <fcntl.h> // open
#include <stdio.h>

int main() {
  close(1); // close standard out
  open("log.txt", O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR);
  puts("Captain's log");
  chdir("/usr/include");
  execl("/bin/ls", "ls", ".", (char *)NULL); 
  perror("exec failed");
  return 0;
}

当我检查 log.txt 时,我找不到“船长的日志”。我认为它在 execl 之前运行,因此它应该在那里!

4

1 回答 1

0

您正在将其写入标准输出,为什么希望它在文件中?

如果你想重定向stdout只是使用freopen()

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

#include <unistd.h>

int main()
{
    FILE *file;

    file = freopen("log.txt", "w", stdout);
    if (file == NULL)
        return -1;

    printf("Captain's log");
    chdir("/usr/include");

    if (execl("/bin/ls", "ls", ".", NULL) != 0)
        perror("exec failed");
    fclose(file);

    return 0;
}
于 2015-02-23T00:25:51.340 回答