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

如何将system("openssl enc -aes-128-cbc -k secret -P -md sha1 > FILENAME")输出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没有控制台,我需要将输出redirect到一个文本文件,并从文件中获取密钥,以用于encryption/解密。

首先:要知道,我不认为你可以使用system(3)在没有监狱破坏的iOS。 但我不确定,所以我会解释如何做到这一点:

这有点棘手。

为了实现它,你必须知道每个进程都有三个文件描述符打开:一个用于读取( stdinstdin )和两个用于写入( stdoutstdout ,标准错误输出为stderr )。 他们有fd数字0( stdin ),1( stdout )和2( stderr )。

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

  • 第一, fork(2)的过程。 在subprocess的父进程waitpid(2)中。
  • 在subprocess中:
    • 重新打开( freopen(3)stdoutstderr到你想要输出被redirect的文件。
    • 使用execve(2)来执行你想调用的程序
    • 当命令终止的时候,父进程得到一个SIGCHLD,并且waitpid(2)应该返回

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

希望这有助于,如果你有更多的问题,问:-)

更新:因为OP只是想获得输出,而不是特定的文件,你可以使用popen(3)

 int status; char value[1024]; FILE *fp = popen("openssl enc -aes-128-cbc -k secret -P -md sha1", "r"); if (fp == NULL) exit(1); // handle error while (fgets(value, 1024, fp) != NULL) { printf("Value: %s", value); } status = pclose(fp); if (status == -1) { /* Error reported by pclose() */ } else { /* Use macros described under wait() to inspect `status' in order to determine success/failure of command executed by popen() */ }