ccoredumpargv

Parse command line with uncertain number of arguments


I have a concern on how to parse the arguments when number of arguments is not certain.

For example we can consider any core dump application.

On registering an application(ex: store_dump) in /proc/sys/kernel/core_pattern the store_dump application is called whenever a native crash occurs. We can give various options during registration as to what arguments we would like to receive.

My options are - %p %e %s that is (pid, executable file name(thread name), signal number)

So I plan to read the arguments as

argv[1] -> pid
argv[2] -> thread name
argv[3] -> signal number

This owrks fine unless I have space in the thread name. In case if thread name contains space, it is split into two arguments as under.

argv[1] -> pid
argv[2] -> thread name (first part)
argv[3] -> thread name (second part)
argv[4] -> signal number

So how should I write a proper logic to parse these arguments? I cannot always hardcode argv[3] to signal number. Is there a generic way?

One option I see is to keep the thread name at last. But I feel there should be some better solution than this.

Could someone suggest.


Solution

  • Option 1: Change your core pattern to %p %s %e. Since %e is the only thing that can get replaced with whitespace, you can simply consider all the trailing arguments (i.e. argv[i] for i > 2) to make up the thread name.

    Option 2: If you have multiple specifiers that may be replaced with whitespace (e.g. repeated instances of %e, or %h), you can set add magic separators to your arguments which you hope will never appear as part of a thread name, and then look for those as you iterate over the arguments:

    |store_dump MAGIC1 %p MAGIC2 %e MAGIC3
    

    Neither option is perfect in the sense that any whitespace in the thread name is normalized, so you cannot reconstruct the actual name accurately. For example, you cannot distinguish threads that only differ in the length of their embedded whitespace runs.