cswift3.2

Call C function in swift3 fork(), system()


How to call fork() and system() in swift?

var pid = fork() // Error: Missing argument for parameter #1 in call

var r = system() //Error: fork()' is unavailable: Please use threads or posix_spawn*()

Tried

var param: Int8
var s = system(&param)

as well but it is giving different error - 'system' is unavailable in Swift: Use posix_spawn APIs or NSTask instead.

I tried to use posix_param. But getting another error here is my code:-

var pid: pid_t

var status: Int32
posix_spawn(&pid, "", nil, nil, [], nil);
waitpid(pid, &status, WEXITED);
if pid >= 0 {
    return true

}

Errors: 1) Address of variable 'pid' taken before it is initialized. 2) Address of variable 'status' taken before it is initialized.

Objective C version of this code which is working.

int pid = fork();
if(!pid){
    exit(0);
 }
 if(pid>=0)
  {
     return YES;
  }

Here


Solution

  • I got it!

    After initializing pid to -1 and status to 0.

    For jailbroken device pid value is greater than 0 whereas for non jailbroken device pid value remains unchanged.