Skip to content

Instantly share code, notes, and snippets.

@msymt
Last active July 4, 2022 08:06
Show Gist options
  • Save msymt/eb9f41fdfe63dc12eae0cac60bd90663 to your computer and use it in GitHub Desktop.
Save msymt/eb9f41fdfe63dc12eae0cac60bd90663 to your computer and use it in GitHub Desktop.
How to call libc library in C#
$uname -a
Linux 4b44f62b3201 5.10.104-linuxkit #1 SMP Wed Mar 9 19:05:23 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
$ mono -V
Mono JIT compiler version 6.12.0.179 (tarball Tue May 17 21:33:45 UTC 2022)
Copyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com
        TLS:           __thread
        SIGSEGV:       altstack
        Notifications: epoll
        Architecture:  amd64
        Disabled:      none
        Misc:          softdebug
        Interpreter:   yes
        LLVM:          yes(610)
        Suspend:       hybrid
        GC:            sgen (concurrent by default)
$ mono Main.exe
return from fork() is 92
pid is 89
end!
return from fork() is 0
pid is 92
end!
using System;
using System.Runtime.InteropServices;
namespace PInvokeSamples
{
public static class Program
{
[DllImport("libc.so.6")]
private static extern int fork();
[DllImport("libc.so.6")]
private static extern int getpid();
public static void Main(string[] args)
{
int pid, ret;
if((ret = fork()) == -1){
Console.WriteLine("fork() failed.");
return ;
}
// Invoke the function and get the process ID.
pid = getpid();
Console.WriteLine("return from fork() is " + ret);
Console.WriteLine("pid is " + pid);
Console.WriteLine("end!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment