]> git.ipfire.org Git - thirdparty/suricata.git/commitdiff
examples/lib: create threadvars from main thread
authorJason Ish <jason.ish@oisf.net>
Mon, 30 Sep 2024 22:34:04 +0000 (16:34 -0600)
committerVictor Julien <victor@inliniac.net>
Tue, 1 Apr 2025 08:17:05 +0000 (10:17 +0200)
This also allows us to remove the sleep, as the ThreadVars are now
guaranteed to be created before PostInit.

Ticket: #7240

examples/lib/custom/main.c

index 34d65d74cb7d38f21e57dc36b7159da6155e4261..b910b328874265101db0e5bec24930a2a11ff3c4 100644 (file)
 
 static int worker_id = 1;
 
+/**
+ * Struct to pass arguments into a worker thread.
+ */
+struct WorkerArgs {
+    ThreadVars *tv;
+    char *pcap_filename;
+};
+
 /**
  * Release packet callback.
  *
@@ -57,13 +65,8 @@ static void ReleasePacket(Packet *p)
  */
 static void *SimpleWorker(void *arg)
 {
-    char *pcap_file = (char *)arg;
-
-    /* Create worker. */
-    ThreadVars *tv = SCRunModeLibCreateThreadVars(worker_id++);
-    if (!tv) {
-        pthread_exit(NULL);
-    }
+    struct WorkerArgs *args = arg;
+    ThreadVars *tv = args->tv;
 
     /* Start worker. */
     if (SCRunModeLibSpawnWorker(tv) != 0) {
@@ -71,7 +74,7 @@ static void *SimpleWorker(void *arg)
     }
 
     /* Replay pcap. */
-    pcap_t *fp = pcap_open_offline(pcap_file, NULL);
+    pcap_t *fp = pcap_open_offline(args->pcap_filename, NULL);
     if (fp == NULL) {
         pthread_exit(NULL);
     }
@@ -194,16 +197,18 @@ int main(int argc, char **argv)
      * file as argument. This needs to be done in between SuricataInit
      * and SuricataPostInit. */
     pthread_t worker;
-    if (pthread_create(&worker, NULL, SimpleWorker, argv[argc - 1]) != 0) {
+    ThreadVars *tv = SCRunModeLibCreateThreadVars(worker_id++);
+    if (!tv) {
+        FatalError("Failed to create ThreadVars");
+    }
+    struct WorkerArgs args = {
+        .tv = tv,
+        .pcap_filename = argv[argc - 1],
+    };
+    if (pthread_create(&worker, NULL, SimpleWorker, &args) != 0) {
         exit(EXIT_FAILURE);
     }
 
-    /* Need to introduce a little sleep to allow the worker thread to
-     * initialize before SuricataPostInit invokes
-     * TmThreadContinueThreads().  This should be handle at the API
-     * level. */
-    usleep(100);
-
     SuricataPostInit();
 
     /* Shutdown engine. */