2014-02-10 66 views
0

我想在我的Mac上運行簡單的Objective-C CGI程序。我使用Apache2並運行OS X Mountain Lion(如果有的話)。就拿下面的代碼:運行一個簡單的目標C可執行文件爲Apache CGI

#import <Foundation/Foundation.h> 

int main(int argc, const char * argv[]) 
{ 

    @autoreleasepool { 

     // insert code here... 
     NSLog(@"Content-type: text/plain\r\n"); 
     NSLog(@"From Cupertino, CA, we say, 'hello, World!'\r\n"); 

    } 
return 0; 
} 

我編譯上面的代碼,並複製可執行的CGI目錄,具有.cgi擴展名重命名它,並給它運行的權限。

我在Apache上使用了相當基本的設置,並且在我的httpd.conf中,我確保使用Option s ExecCGI作爲指令,並且我取消註釋AddHandler cgi-script .cgi,以便它可以運行CGI腳本。它工作時,我跑了一個Python CGI腳本,但運行我可執行文件時返回錯誤:

90 [Sun Feb 09 20:01:33 2014] [error] [client ::1] 2014-02-09 20:01:33.247 testCGI.cgi[1498:707] Content-type: text/plain\r 
2991 [Sun Feb 09 20:01:33 2014] [error] [client ::1] 2014-02-09 20:01:33.248 testCGI.cgi[1498:707] From Cupertino, CA, we say, 'hello, World!'\r 
2992 [Sun Feb 09 20:01:33 2014] [error] [client ::1] Premature end of script headers: testCGI.cgi 

任何想法,爲什麼我得到Premature end of script headers: testCGI.cgi

在此先感謝。

回答

1

這是因爲NSLog寫入stderr而不是stdout。您最好使用NSFileHandle的類別方法+fileHandleWithStandardOutput來執行此操作。像:

#import <Foundation/Foundation.h> 

int main(int argc, const char * argv[]) 
{ 
    @autoreleasepool { 
     NSFileHandle *stdout = [NSFileHandle fileHandleWithStandardOutput]; 
     // don't use \r\n, but \n\n else you got an error "malformed header from script. Bad header=" 
     NSData *data = [@"Content-type: text/html\n\n" dataUsingEncoding:NSASCIIStringEncoding]; 
     [stdout writeData: data]; 

     data = [@"From Cupertino, CA, we say, 'hello, World!'\n\n" dataUsingEncoding:NSASCIIStringEncoding];  
     [stdout writeData: data]; 
    } 
    return 0; 
} 
+0

謝謝@Emmanuel。我可能應該閱讀(除其他外):https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference.html – topmulch

+0

@topmulch你是歡迎,是的,閱讀文檔通常是一個好主意:) – Emmanuel

相關問題