How can I detach process from Elixir System.cmd/2 before command ends? - operating-system

I'm trying to run this (script.exs):
System.cmd("zsh", ["-c" "com.spotify.Client"])
IO.puts("done.")
Spotify opens, but "done." never shows up on the screen. I also tried:
System.cmd("zsh", ["-c" "nohup com.spotify.Client &"])
IO.puts("done.")
My script only halts when I close the spotify window. Is it possible to run commands without waiting for it to end?

One should not spawn system tasks in a blind hope they would work properly. If the system task crashes, some actions should be taken in the calling OTP process, otherwise sooner or later it’ll crash in production and nobody would know what had happened and why.
There are many possible scenarios, I would go with Task.start_link/1 (assuming the calling process traps exits,) or with Task.async/1 accompanied by an explicit Task.await/1 somewhere in the supervision tree.
If despite everything explained above you don’t care about robustness, use Kernel.spawn/1 like below
pid = spawn(System, :cmd, ~w|zsh -c com.spotify.Client|)
# Process.monitor(pid) # yet give it a chance to handle errors
IO.puts("done.")

Related

Connecting FluidEnter/FluidExit at run-time

I am toying with the FluidEnter/FluidExit. So in a simple form, here is what I am trying to do:
I created in Main an empty population of agent called Terminal. For now, in Terminal, there is only a fluidEnter connected to a fluidExit (very simple)
enter image description here
Now, on startup, I want to fill this population and set up the proper connections (the terminals are ordered).
So, on startup, I call a function init(), whose body start with Terminal t = add_terminals(); (I have only one terminal for now, just toying with things)
In Main, obviously, I also have a fluidEnter and a fluidExit. I would like to connect the fluidExit of Main to the fluidEnter of the terminal t, and the fluidExit of the terminal t to the fluidEnter of Main, so code (still in init()) looks like
fluidExit.set_fluidEnter(t.fluidEnter);
t.fluidExit.set_fluidEnter(fluidEnter);
I get an exception so obviously, I am doing something wrong. Any idea?
I think the set_fluidEnter function is deprecated or just non-functional.
Instead, you should do:
fluidExit.connect(t.fluidEnter);
So just replace set_fluidEnter with connect... nothing else.
That should do the trick
I was going down the same path as you a couple of months ago. Yes... .connect() works great. It even works as a gate. If it is disconnected, then fluid stops at the exit. Once connected, fluid starts to flow again. It is very slick.

How to make afl-fuzz not skip test cases when a timeout is reached

I am currently trying to fuzz a PDF viewer with the AFL fuzzer (American Fuzzy Lop).
My problem is quite simple, afl-fuzz expect the application to take an input and close after processing it. But, the PDF viewer is intended to open the document and stay open until closed. The result is that afl-fuzz reach the timeout for all initial inputs and decide to stop here.
...
[*] Validating target binary...
[*] Attempting dry run with 'id:000000,orig:myPDFsample00.pdf'...
[*] Spinning up the fork server...
[+] All right - fork server is up.
[!] WARNING: Test case results in a timeout (skipping)
[*] Attempting dry run with 'id:000001,orig:myPDFsample01.pdf'...
[!] WARNING: Test case results in a timeout (skipping)
[*] Attempting dry run with 'id:000002,orig:myPDFsample02.pdf'...
[-] PROGRAM ABORT : All test cases time out, giving up!
Location : perform_dry_run(), afl-fuzz.c:2883
I would like to know how to tell AFL to consider that reaching the timeout and get the program terminated is a "normal" behavior for the test case.
In fact, the usual way to do seems to simply instrument the code of the software you are looking at by adding an exit(0) after the parsing.
It seems quite basic, but I works...
The other way could be to change the meaning of a timeout in the AFL software. But, then, it won't detect 'hangs' when your software might enter a never ending loop.
So, the best way really seems to add an exit(0) (or return 0 if you are in main()) inside your target software just after the parsing is done.

Moving from file-based tracing session to real time session

I need to log trace events during boot so I configure an AutoLogger with all the required providers. But when my service/process starts I want to switch to real-time mode so that the file doesn't explode.
I'm using TraceEvent and I can't figure out how to do this move correctly and atomically.
The first thing I tried:
const int timeToWait = 5000;
using (var tes = new TraceEventSession("TEMPSESSIONNAME", #"c:\temp\TEMPSESSIONNAME.etl") { StopOnDispose = false })
{
tes.EnableProvider(ProviderExtensions.ProviderName<MicrosoftWindowsKernelProcess>());
Thread.Sleep(timeToWait);
}
using (var tes = new TraceEventSession("TEMPSESSIONNAME", TraceEventSessionOptions.Attach))
{
Thread.Sleep(timeToWait);
tes.SetFileName(null);
Thread.Sleep(timeToWait);
Console.WriteLine("Done");
}
Here I wanted to make that I can transfer the session to real-time mode. But instead, the file I got contained events from a 15s period instead of just 10s.
The same happens if I use new TraceEventSession("TEMPSESSIONNAME", #"c:\temp\TEMPSESSIONNAME.etl", TraceEventSessionOptions.Create) instead.
It seems that the following will cause the file to stop being written to:
using (var tes = new TraceEventSession("TEMPSESSIONNAME"))
{
tes.EnableProvider(ProviderExtensions.ProviderName<MicrosoftWindowsKernelProcess>());
Thread.Sleep(timeToWait);
}
But here I must reenable all the providers and according to the documentation "if the session already existed it is closed and reopened (thus orphans are cleaned up on next use)". I don't understand the last part about orphans. Obviously some events might occur in the time between closing, opening and subscribing on the events. Does this mean I will lose these events or will I get the later?
I also found the following in the documentation of the library:
In real time mode, events are buffered and there is at least a second or so delay (typically 3 sec) between the firing of the event and the reception by the session (to allow events to be delivered in efficient clumps of many events)
Does this make the above code alright (well, unless the improbable happens and for some reason my thread is delayed for more than a second between creating the real-time session and starting processing the events)?
I could close the session and create a new different one but then I think I'd miss some events. Or I could open a new session and then close the file-based one but then I might get duplicate events.
I couldn't find online any examples of moving from a file-based trace to a real-time trace.
I managed to contact the author of TraceEvent and this is the answer I got:
Re the exception of the 'auto-closing and restarting' feature, it is really questions about the OS (TraceEvent simply calls the underlying OS API). Just FYI, the deal about orphans is that it is EASY for your process to exit but leave a session going. This MAY be what you want, but often it is not, and so to make the common case 'just work' if you do Create (which is the default), it will close a session if it already existed (since you asked for a new one).
Experimentation of course is the touchstone of 'truth' but I would frankly expecting unusual combinations to just work is generally NOT true.
My recommendation is to keep it simple. You need to open a new session and close the original one. Yes, you will end up with duplicates, but you CAN filter them out (after all they are IDENTICAL timestamps).
The other possibility is use SetFileName in its intended way (from one file to another). This certainly solves your problem of file size growth, and often is a good way to deal with other scenarios (after all you can start up you processing and start deleting files even as new files are being generated).

Invoke process activity not logging any error in log file

I am trying to use Invoke process to invoke an executable from my windows workflow in my TFS 2010 build.
But when I am looking at the log file it is not logging any error.
I did use WriteBuildMessage and WriteBuildwarning inside my invoke process activity.
I also set the filename,workingdirectory etc in activity.
Can someone please point out why it is not logging?
You can do something like this:
In this case you have to ensure that Message are set as follows:
With those parameters set as depicted, I catch what you seem to be after.
Furthermore, you can check in the Properties of your InvokeProcess: Set the Result into a string-variable and then set in a subsequent WriteBuildMessage this string-variable to be the Message. This way, you 'll additionally catch the return of your invoked process.
EDIT
Another common thing that you 've possibly overlooked is the BuildMessageImportance: if it is not set as High, messages do NOT appear under default Logging Verbosity (= Normal). See here for some background.
In your Invoke Process, you want to set the Result property to update a variable (returns an Int, so lets call it ExitCode), under your Invoke Process (but still in the Agent Scope) you can drop in an If, so you can set the condition of this to ExitCode <> 0 and do whatever you like on a failure (such as failing the build).
Also, as a note, if your WriteBuildMessage is not showing anything in your log, you need to set the Importance to Microsoft.TeamFoundation.Build.Client.BuildMessageImportance.High, anything lower and it wont show in the Normal logging level.

perl: Launch process with system(), then check if its running under a specific display number

I have a locked down "kiosk" terminal server.
This terminal server has a perl script as its .Xsession, and launches a Tk interface. When that Tk interface is done, the perl script launches "process2" and lets the user interact with "process2" (which is a graphical application).
If a user tampers with "process2", and make it crash, the user might be able to access the underlying desktop, therefore I would want to check if "process2" is running, and if "process2" is not running on $display, I would want to just execute logout (which would logout the display the perl script is currently running as).
Since the system is running 10 instances of "process2" to 10 different users simultanuosly, I cant just check if "process2" is running on the system with "ps" or someting like that. I need to check if "process2" is running under that specific display $display.
Note that all 10 users log on as the same username in all sessions, so I cannot check all processes run by a specific user, that would return all 10 instances too.
Like:
system("process2 &");
while(1) {
sleep(1);
if (is_it_running("process2", $display) == false) {
system("logout &");
}
}
Its the function "is_it_running" that I need to get to know how it should look.
$display can either contain the raw display number, like this: ":1.0", or it can contain the display number parsed out, like this: "1".
If you use fork and exec instead of system("...&"), you can store the Process IDs of your child processes and more directly check their status. See also perlipc.
Why not just run process2 in the foreground? Then your perl script won't get control back until it's done executing, at which point it can exit:
system("process2");
system("logout");
Of course, if that's the entire script, maybe a bash script would make more sense.
I solved it after many attempts.
Did a piped open
$pidofcall = open(HANDLE, "process2|");
Then I did whatever I did need to do, and I made the server send a signal to me if it loses connection with process2. If I did need to bang out, I simply did a "goto killprocess;" Then I simply had:
killprocess:
kill(9,$pidofcall);
close(HANDLE);
$mw->destroy;
system("logout");