Mavlink_shell task does not exit after destructor

I was attempting to stop modules during calibration to free memory using the mavlink_shell in mag_calibration.cpp.

I added the following code to do_mag_calibration() to stop the vtol module before attempting calibration.

if (!mavlink_shell) {
		mavlink_shell = new MavlinkShell();

		if (!mavlink_shell){
			PX4_WARN("Could not free memory for calibration.");
			return 0;
		}
		else{
			int ret = mavlink_shell->start();
			if (ret != 0) {
				PX4_ERR("Failed to start shell (%i)", ret);
				delete mavlink_shell;
				mavlink_shell = nullptr;
			}
			else {
				PX4_INFO("Stopping unnecessary applications");
				uint8_t command0[] = "vtol_att_control stop\r";

				mavlink_shell->write(command0, sizeof(command0)/sizeof(uint8_t));

			}
		}
	}

	sleep(1);

	if (mavlink_shell) {
		delete mavlink_shell;
		mavlink_shell = nullptr;
	}

	return 0;

Unfortunately the “top” command shows that mavlink_shell is still running. If I attempt calibration again another mavlink_shell task starts eating up more memory.

I even see the text “Stopping mavlink shell” printed to the shell indicated the MavlinkShell destructor is called.

Any idea how I get this thread to stop and free up the memory?