2016-04-20 30 views
1

我試圖在OSX上使用fork和execv啓動預覽。當我使用fork和execv時,在dock中彈出預覽圖標,但屏幕上不顯示任何內容。該控制檯還顯示下面的兩條錯誤消息。如何使用fork和execv以編程方式啓動預覽?

4/20/16 12:18:23.276 PM iconservicesagent[319]: -[ISGenerateImageOp generateImageWithCompletion:] Failed to composit image for descriptor <ISBindingImageDescriptor: 0x7f85aa50b890>. 
4/20/16 12:18:23.276 PM quicklookd[1959]: Error returned from iconservicesagent: (null) 

下面是一些代碼來重現該問題,請注意你將不得不更換 的args陣列中的硬編碼文件路徑爲您的系統有效的PDF文件的路徑。

#include <stdio.h> 
#include <unistd.h> 
#include <string.h> 
#include <stdlib.h> 
#include <errno.h> 
#include <stdint.h> 

int main(int argc, char *argv[]) 
{ 
    pid_t pid = 0; 
    int32_t rtrn = 0; 

    pid = fork(); 
    if(pid == 0) 
    { 
     char * const args[] = {"https://stackoverflow.com/users/nah/desktop/file.pdf", NULL}; 

     rtrn = execv("/Applications/Preview.app/Contents/MacOS/Preview", args); 
     if(rtrn < 0) 
     { 
      printf("Can't execute target program: %s\n", strerror(errno)); 
      _exit(-1); 
     } 

     _exit(0); 
    } 
    else if(pid > 0) 
    { 
     int32_t status = 0; 

     while(waitpid(-1, &status, 0) > 0) 
     { 

     } 
    } 
    else 
    { 
     printf("Can't create child proc: %s\n", strerror(errno)); 
     return (-1); 
    } 

    return (0); 
} 

但是如果我更換所有的叉子和execv代碼,並使用system(3)就像在下面的例子中,預覽打開並顯示就好了,並有在控制檯沒有錯誤消息。那麼如何使用fork和execv來啓動預覽,而不是使用system(3)或必須使用Objective-C?

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

int main(int argc, char *argv[]) 
{ 
    pid_t pid = 0; 
    int32_t rtrn = 0; 

    rtrn = system("/Applications/Preview.app/Contents/MacOS/Preview /users/nah/desktop/file.pdf"); 
    if(rtrn < 0) 
    { 
     printf("System: %s\n", strerror(errno)); 
     return (-1); 
    } 

    return (0); 
} 

回答

0

您還需要額外的參數設置Mac OS X的應用系統提供給main(),但你不應該做任何這樣的:

預覽可能會或可能不會是默認的PDF對於正在運行的系統的查看器,如果不是,恭喜,您現在有一個令人困惑,可能是憤怒的用戶。

如果你不想使用Objective-C,你想要做的是system("open /path/to/file.pdf");。這將照顧所有棘手的業務,搞清楚什麼應用程序使用,其中它是和如何來啓動它。

+0

這是一個模糊器,我特別想推出和測試預覽,所以我不擔心用戶,也不想等待Preview使用system()。 – 2trill2spill

+0

@ 2trill2spill'open'應該很快恢復控制,但如果速度不夠快,你可以試試'system(「open /file.pdf &")';應該更快。 –

+0

我想用fork的原因是我有pid的預覽,所以我可以在啓動後立即殺死它,我怎樣才能使用系統()或其他殺死預覽pid。 – 2trill2spill

相關問題