如何捕获system()启动的进程的标准输出

时间:2013-02-07 13:36:54

标签: iphone ios io-redirection

如何将system("openssl enc -aes-128-cbc -k secret -P -md sha1 > FILENAME")的输出保存到文件中。

我尝试了以下内容:

NSArray *paths = NSSearchPathForDirectoriesInDomains

(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",

                      documentsDirectory];

NSString *str=[NSString stringWithFormat:@"openssl enc -aes-128-cbc -k secret -P -md sha1 > %s",[fileName UTF8String]];
NSLog(@"AES Key is %@",str);
system([str UTF8String]);

NSString *strAES = [NSString stringWithContentsOfFile:fileName encoding:nil error:nil];
NSLog(@"strAES Key is %@",strAES);

NSString *strAESKey=[[[[strAES componentsSeparatedByString:@"\n"] objectAtIndex:1] componentsSeparatedByString:@"="] objectAtIndex:1];
NSLog(@"strAESKey Key is %@",strAESKey);

// NSString *content = @"One\nTwo\nThree\nFour\nFive";
  [str writeToFile:fileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];`

我哪里错了?

system()函数将输出发送到控制台,但由于iPhone没有控制台,我需要将输出重定向到文本文件并从文件中获取密钥以将其用于加密/解密

1 个答案:

答案 0 :(得分:0)

首先:请注意,我不认为您可以在不受监狱的iOS上使用system(3)。但我不确定,所以我会解释如何做到这一点:

这有点棘手。

要实现它,您必须知道每个进程都有三个文件描述符打开:一个用于读取(stdin用于标准输入),两个用于写入(stdout用于标准输出和{{ 1}}用于标准错误输出)。它们的fd编号为0(stderr),1(stdin)和2(stdout)。

要将标准输出或标准错误重定向到程序中的文件,您必须执行以下操作:

  • 首先,stderr这个过程。在子进程的父进程fork(2)中。
  • 在子进程中:
    • 重新打开(waitpid(2)freopen(3)stdout到您想要重定向输出的文件。
    • 使用stderr执行您要调用的程序
    • 当命令终止时,父级获得SIGCHLD并且execve(2)应该返回

括号中的数字描述了该函数的手册页(waitpid(2),例如)中的章节。

希望这有帮助,如果您有更多问题,请询问: - )

更新:由于OP只想获取输出而不是特定的文件,因此您可以使用man 2 waitpid

popen(3)
相关问题