Call piece of c++ code once in multiprocess environment - linux

I am currently developing some piece of code which should execute once in multiprocess environment.
//foo.cpp --> Shared library linked by both process1 and process2
void foo() { std::cout << "foo : Makesure I call only once in multiprocess environment \n"; }
//process1.cpp
int main() { foo(); }
//process2.cpp
int main() { foo(); }
I need to call foo() function only once either by process1/process2 in C++ environment.
Only Alternative solution I can think off is to creating dummy_file inside foo at firsttime and print message, If file already exist should not print message.
any suggestion would be appreciated

Only Alternative solution I can think of is to creating dummy_file inside foo at firsttime and print message, If file already exist should not print message.
Yes. This is a viable alternative. If you were on Windows I'd say it would be better to have a Registry entry instead so the file can't easily/accidentally be deleted, but I see you've tagged the question for linux.
See this article on IPC for Linux for other solutions than using a file.

Related

How to set pthread name at the time of creation?

I am using pthread in my program. For creation using pthread_create(). Right after creation I am using pthread_setname_np() to set the created thread's name.
I am observing that the name I set takes a small time to reflect, initially the thread inherits the program name.
Any suggestions how I can set the thread name at the time I create the thread using pthread_create()? I researched a bit in the available pthread_attr() but did not find a function that helps.
A quick way to reproduce what I am observing, is as follows:
void * thread_loop_func(void *arg) {
// some code goes here
pthread_getname_np(pthread_self(), thread_name, sizeof(thread_name));
// Output to console the thread_name here
// some more code
}
int main() {
// some code
pthread_t test_thread;
pthread_create(&test_thread, &attr, thread_loop_func, &arg);
pthread_setname_np(test_thread, "THREAD-FOO");
// some more code, rest of pthread_join etc follows.
return 0;
}
Output:
<program_name>
<program_name>
THREAD-FOO
THREAD-FOO
....
I am looking for the first console output to reflect THREAD-FOO.
how I can set the thread name at the time I create the thread using pthread_create()?
That is not possible. Instead you can use a barrier or mutex to synchronize the child thread until it's ready to be run. Or you can set the thread name from inside the thread (if any other threads are not using it's name).
Do not to use pthread_setname_np. This is a nonstandard GNU extension. The _np suffix literally means "non-portable". Write portable code and instead use your own place where you store your thread names.
Instead of pthread_setname_np(3) you can use prctl(2) with PR_SET_NAME. The only limitation with this function is that you can only set the name of the calling process/thread. But since your example is doing exactly that, there should be no problem with this solution AND it's a portable standard API.

How to make Unified FFI work in Pharo

I have a C function that copies a string into a buffer that's been passed to it:
void get_machine(char *buf) {
/* do something to acquire the machine string */
strcpy(buf, machine_string);
}
I want to call it from Pharo:
machine := String new: 256.
self ffiCall: #( void get_machine(String machine) ) module: 'ffilibc.so'.
But this doesn't work: the contents of machine_string do not get copied into machine. What is the correct way to do this?
I learned that the String buffer is immutable. That's why the C function couldn't write to it.
The solution is to use a ByteArray.
"It does not work" is too vague. Can you tell me what's your error?
in case is "module not found", this is because you need to give the full path (unless library is in same place as the image). Also remember the library needs to be compiled for 32bits.

Function Hooking with C++

If I understand correctly, with this, functions within a program can be tracked down and modified.
Let's just say I had a .exe in c++ that just does the following in a loop:
void func()
{
printf("A");
}
What tools would I need to intercept the function within that .exe and instead change the function to do something like printf("B") instead?

Swift: Async callback in command line utility [duplicate]

I am writing a command line application in Swift using a third-party framework that (if I understand the code correctly) relies on GCD callbacks to complete certain actions when a socket receives data. In order to better understand the framework, I have been playing around with a sample Cocoa application the framework's author wrote to go along with the framework.
Because the sample application is a Cocoa application, the run loops are handled automatically. I'm including snippets of code from the sample application (MIT license) to give an idea of how it works:
class AppDelegate: NSObject, NSApplicationDelegate {
var httpd : Connect!
func startServer() {
httpd = Connect()
.onLog {
[weak self] in // unowned makes this crash
self!.log($0)
}
.useQueue(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0))
...
httpd.listen(1337)
}
...
func applicationDidFinishLaunching(aNotification: NSNotification?) {
startServer()
...
}
}
I'd like to modify the sample application to run from the command line. When I put the startServer() function into a command line application, it runs, but the socket is immediately closed after it is opened, and the program finishes executing with an exit code 0. This is expected behavior, as there are no run loops in an Xcode command line project, and thus the program doesn't know to wait for the socket to receive data.
I believe the correct way to get the socket to stay open and the program to continuously run would be to put the main thread in a CFRunLoop. I have looked over Apple's documentation and, except for the basic API reference, there is nothing on threading in Swift. I have looked at third party resources, but they all involve alternate threads in iOS and Cocoa applications. How do I properly implement a CFRunLoop for the main thread?
It seems like Martin R's answer should work, however I was able to get the socket to stay open with a single function call. At the end of the startServer() function, I put the line:
CFRunLoopRun()
Which worked.
The NSRunLoop Class Reference
has an example for a simple runloop:
BOOL shouldKeepRunning = YES; // global
NSRunLoop *theRL = [NSRunLoop currentRunLoop];
while (shouldKeepRunning && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
which can be translated to Swift:
var shouldKeepRunning = true // global
let theRL = NSRunLoop.currentRunLoop()
while shouldKeepRunning && theRL.runMode(NSDefaultRunLoopMode, beforeDate: NSDate.distantFuture()) { }
Alternatively, it might be sufficient to just call
dispatch_main()
Update for Swift 3.1:
let theRL = RunLoop.current
while shouldKeepRunning && theRL.run(mode: .defaultRunLoopMode, before: .distantFuture) { }
or
dispatchMain()

SDL_AddTimer in which way it is used to avoid multithreading problems

Wiki Link for SDL_AddTimer
The wiki document for SDL_AddTimer claims that
"Note that it is possible to avoid the multithreading problems with SDL timers by giving to userevent.data1 the address of a function you want to be executed and to userevent.data2 its params, and then deal with it in the event loop."
How it is used to avoid multithreading problem?.
Can someone explain what is it i am unable to understand the statement ?
The first example assumes the working function, i.e. the function you want to execute ( my_function() ), resides in the my_callbackfunc() function.
SDL_AddTimer() specifies: Use this function to set up a callback function to be run on a separate thread after the specified number of milliseconds has elapsed.
This will introduce concurrency problems with my_function().
The solution (second example), assumes the event polling thread is the same thread that added the timer, and calls the function in that thread.
I've read that SDL documentation as well, and it makes a really bad suggestion for its "workaround". Specifically, it recommends casting a function address to a void pointer. This is not portable! Do not do it and please read
https://isocpp.org/wiki/faq/pointers-to-members#cant-cvt-fnptr-to-voidptr
If you feel that you must do this (or something like it) then I'd suggest wrapping the function pointer inside a struct/class.
struct Wrapper
{
void (*f)(void*);
Wrapper(void (*F)(void*)) { f = F; }
};
Create the wrapper when you want to push the custom event
SDL_Event event;
event.user.data1 = (void*) new Wrapper(your_function);
event.user.data2 = your_function_arg;
SDL_PushEvent(&user);
Then in your main loop, do the call, delete the wrapper
SDL_WaitEvent(&event);
if (event.type == SDL_USEREVENT)
{
Wrapper *p = ((Wrapper*) event.user.data1)
p->f(event.user.data2);
delete p;
}

Resources